Binding collections in MVC

人盡茶涼 提交于 2019-11-30 23:15:07

I believe that input tags associated with items in a collection (when the model itself is not a collection) need to have an index in the name attribute before you can bind posted data to a view model. Here is the way I usually accomplish this...

<% 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've also used the template as suggested by Shea, but I have a tad more code trying to force it to render 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 from Phil Haack on the topic.

Try using this:

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

Then, make a shared editor template with a model type of TeamMember. MVC should handle binding everything back to your viewmodel on post for you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!