How to get dynamically added values ​​from a view to a controller in ASP.NET MVC?

I am learning some concepts in asp.net mvc. I use the entity structure and visual studio of 2013. I am creating a demo application for training. I created a model according to this link. Models are as follows. Below is a model of the course. The course has a department as a 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 a department model. The department model is simple. This is due to the 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 used scafolding and created controllers and views with CRUD functionality. I can create a department and viewing courses. Now I need to assign several courses when creating departments. Therefore, I created this presentation 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 take more courses when creating a department. The result is as follows. View

The plus button has a script, which is from my previous question here . The script uses jquery and clones the dropdown menu and adds it back.

The problem starts here. When I add more than one drop-down list, say 3, I get null in the controller, although I get three elements, only one element matters, the others null. See Image for more explanation.

Image for clarification.

Why is this happening? PS: I could ignore real-time scenarios, as this is a demo application for learning and eliminating concepts from one to many relationships with entity infrastructure along with using MVC.

0
source share

Source: https://habr.com/ru/post/1246696/


All Articles