Getting the kids collection for the parent model HttpPost update

This question may be a repeat of the previous question, if there is, please send a link. In any case, I will continue this post.

I have this model:

public class Employee { //omitted for brevity public virtual ICollection<ProfessionalExperience> ProfessionalExperiences { get; set; } public virtual ICollection<EducationalHistory> EducationalHistories { get; set; } } public class ProfessionalExperience { // omitted for brevity } public class EducationalHistory { // omitted for brevity } 

I show in my view with this action:

 [HttpGet] public ActionResult Edit(int id) { using(var context = new EPMSContext()) { var employees = context.Employees.Include("ProfessionalExperiences").Include("EducationalHistories"); var employee = (from item in employees where item.EmployeeId == id && item.IsDeleted == false select item).FirstOrDefault(); return View(employee); } } 

Here is my view:

 @using(Html.BeginForm()) { <div class="editor-label">First Name:</div> <div class="editor-field">@Html.TextBoxFor(x => x.FirstName)</div> <div class="editor-label">Middle Name:</div> <div class="editor-field">@Html.TextBoxFor(x => x.MiddleName)</div> @foreach(var item in Model.ProfessionalExperiences) { Html.RenderPartial("ProfExpPartial", item); } @foreach(var item in Model.EducationalHistories) { Html.RenderPartial("EducHistPartial", item); } <input type="submit" value="Save" /> } 

I represent a child collection in a view using foreach and using a partial view for each collection.

When my Edit Message action is called, the employee model has child collections set to null.

 [HttpPost] public ActionResult Edit(Employee employee) { using(var context = new EPMSContext()) { } return View(); } 

What am I missing to get child collections correctly?

Thanks!

+4
source share
1 answer

I think the problem is with the way MVC expects collection elements to be created (their names in html). Take a look at this SO answer: fooobar.com/questions/756684 / ... , especially the link to the Scott Hanselman post .

Your problem is that if you manually RenderPartial() and make individual calls to RenderPartial() , the input fields will not have indexes, and DefaultModelBinder does not know how to create your collection.

I personally created Editor Templates for the two ViewModel types and used @Html.EditorFor(model => model.EducationalHistories) and @Html.EditorFor(model => model.ProfessionalExperiences) .

+2
source

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


All Articles