Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
556 views
in Technique[技术] by (71.8m points)

model binding - How ASP.NET MVC: How can I bind a property of type List<T>?

Let's say I've the bellow model

public class UserInformation
{
  public List<UserInRole> RolesForUser { get; set; }      
  //Other properties omitted...
}

public class UserInRole
{
  public string RoleName { get; set; }
  public bool InRole { get; set; }
}

On my page I have something like

<%using(Html.BeginForm()){%>
  .../...
  <%for(int i =0; i<Model.InRoles.Cout; i++%>
  <p><%: Html.CheckBox(Model.Roles[i].RoleName, Model.Roles[i].InRole)%></p>
<%}%>

The idea is to be able to check/uncheck the checkbox so that when the form is posted to the action, the action acts appropriately by adding/removing the user from each role.

The problem is when form is posted to the action method, the Roles property (which is a list UserInRole object) doesn't reflect the change made by the user. ModelBinder works properly on the all other properties but 'Roles property'

I wonder how I can do that. I suspect that the name/id given to the checkbox is not appropriate. But, I'm just stack. Maybe I should do it differently.

Thanks for helping

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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) %>

<% } %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...