Linking collections in MVC

I have a view model consisting of an Applicant object and a TeamMember collection. When I send the model back, the collection of the team is always zero. I tried changing the collection from my original IEnumarable to List , but that didn’t affect it. So I changed the Controllers Edit action to accept a FormCollection , and confirmed that there was viewModel["member.FirstName"] in viewModel["member.FirstName"] . I lost why the binding does not work. I tried to clean up the code samples as much as possible, but I am confused by what is missing. Any help is much appreciated!

View model properties

 public class MyViewModel { public Applicant ApplicantInfo { get; set; } public List<TeamMember> TeamMembers { get; set; } } 

controller

 [HttpPost] public ActionResult Edit(MyViewModel viewModel) { // viewModel.ApplicantInfo has the form data // viewModel.TeamMembers = null } 

View

 <% using (Html.BeginForm()) {%> <h3> <a href="#">Applicant Information</a> </h3> <label> City <%: Html.TextBoxFor(m => Model.ApplicantInfo.City)%> </label> <label> State <%: Html.TextBoxFor(m => Model.ApplicantInfo.State)%> </label> <h3> <a href="#">Team</a> </h3> <div> <% foreach (var member in Model.TeamMembers) { %> <div class="editor-field"> <%: Html.DropDownList("member.Type", Model.GetMemberTypes(member.MemberType.TypeId))%> </div> <div class="editor-field"> <%: Html.EditorFor(m => member.FirstName)%> </div> <div class="editor-field"> <%: Html.EditorFor(m => member.LastName)%> </div> <div class="editor-field"> <%: Html.EditorFor(m => member.Title)%> </div> <%} %> </div> <p> <input type="submit" value="Save" /> </p> <% } %> 
+4
source share
2 answers

I believe that input tags associated with items in the collection (when the model itself is not a collection) should have an index in the name attribute before you can bind the published data to the view model. This is how I usually do it ...

 <% for (int i=0; i<Model.TeamMembers.Count; i++) { %> <div class="editor-field"> <%: Html.EditorFor(m => m.TeamMembers[i].FirstName)%> </div> <div class="editor-field"> <%: Html.EditorFor(m => m.TeamMembers[i].LastName)%> </div> <% } %> 

I also used the template suggested by Shea, but I have another code that tries to make it display brackets / indexes.

 <% foreach (var member in Model.TeamMembers) { %> <%: Html.EditorFor(x => member, "TeamMember", "TeamMembers["+(member.Number-1)+"]", new { MemberTypes = Model.GetMemberTypes(member.MemberType.TypeId) })%> <% } %> 

Here is an old but still relevant article by Phil Haack on this topic.

+5
source

Try using this:

 <%: Html.EditorFor(m => m.TeamMembers) %> 

Then create a common editor template with the TeamMember model TeamMember . MVC should handle binding everything back to your view model for the message to you.

+1
source

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


All Articles