问题
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
回答1:
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) %>
<% } %>
回答2:
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>
<%}%>
来源:https://stackoverflow.com/questions/4163783/how-asp-net-mvc-how-can-i-bind-a-property-of-type-listt