I am learning some concepts in asp.net mvc. I am using entity framework and visual studio 2013 community edition. I am creating a demo app for learning. I have created model according to this link. The models are as follows. Below is course model. The course has department as foreign key. A department can have many courses.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ManyItemsDemo2.Models
{
public class Course
{
public int CourseID { get; set; }
public string Title { get; set; }
public string Credits { get; set; }
public int DepartmentID { get; set; }
public virtual Department Department { get; set; }
}
}
This is department model. The department model is simple. It is associated with course model.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ManyItemsDemo2.Models
{
public class Department
{
public Department()
{
this.Cources = new HashSet<Course>();
}
public int DepartmentID { get; set; }
public string Name { get; set; }
public double Budget { get; set; }
public string Administrator { get; set; }
public virtual ICollection<Course> Cources { get; set; }
}
}
There is a context class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace ManyItemsDemo2.Models
{
public class SchoolContext:DbContext
{
public SchoolContext() : base("SchoolContext") { }
public DbSet<Course> Courses { get; set; }
public DbSet<Department> Departments { get; set; }
}
}
Now i have used scafolding and created controllers and views with CRUD functionality. I can create a department and courses in views. Now i need to assign multiple courses while creation of departments. So i created a this view model. Here One department has many courses.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ManyItemsDemo2.Models;
namespace ManyItemsDemo2.ViewModels
{
public class DeptCourses
{
public Department Department { get; set; }
public IEnumerable<Course> Course { get; set; }
}
}
along with this i created a new view. Which can accept more cources while creating department. The view result is like this.
The plus button has a script which is from my earlier question here. The script uses jquery and clones the drop down and adds back.
The problem starts from here. When i add more than one drop down, let say 3, i am receiving null in controller, though i receives three elements, only one element has value, others are null. See the image for more clarification.
Why this happens? PS: I might overlooked real time scenarios as this is demo app for learning and clearing the concepts of one to many relationships with entity framework along with using MVC.