How ASP.NET MVC: How can I bind a property of type List?

后端 未结 2 1987
既然无缘
既然无缘 2020-12-11 13:48

Let\'s say I\'ve the bellow model

public class UserInformation
{
  public List RolesForUser { get; set; }      
  //Other properties omitte         


        
相关标签:
2条回答
  • 2020-12-11 14:22

    I think the problem is how your submitting your form data. For model binding to work it needs the key name with its associated value. The below code based on your code should bind correctly:

    <%using(Html.BeginForm()){%>
      .../...
      <%for(int i =0; i<Model.RolesForUser.Count; i++%>
      <p>
         <%: Html.Hidden("UserInformation.RolesForUser[" + i + "].RoleName", Model.RolesForUser[i].RoleName) %>
         <%: Html.CheckBox("UserInformation.RolesForUser[" + i + "].InRole", Model.RolesForUser[i].InRole) %>
         <%: Model.RolesForUser[i].RoleName %>
      </p>
    <%}%>
    
    0 讨论(0)
  • 2020-12-11 14:25

    You should see Phil Haack's post on model binding to a list. Essentially what you need to is simply submit a bunch of form fields each having the same name.

    <%@ Page Inherits="ViewPage<UserInformation>" %>
    
    <% for (int i = 0; i < 3; i++) { %>
    
      <%: Html.EditorFor(m => m.RolesForUser[i].RoleName) %>
      <%: Html.EditorFor(m => m.RolesForUser[i].InRole) %>
    
    <% } %>
    
    0 讨论(0)
提交回复
热议问题