ASP.NET MVC:如何绑定 List类型的属性?
假设我有以下模型
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; }
}
在我的页面上我有类似的
<%using(Html.BeginForm()){%>
.../...
<%for(int i =0; i<Model.InRoles.Cout; i++%>
<p><%: Html.CheckBox(Model.Roles[i].RoleName, Model.Roles[i].InRole)%></p>
<%}%>
想法是能够选中/取消选中复选框,以便当表单发布到操作时,操作通过在每个表单中添加/删除用户来适当地执行操作角色。
问题是当表单发布到操作方法时,Roles 属性(这是一个 UserInRole 对象列表)不会反映用户所做的更改。 ModelBinder 在所有其他属性上都能正常工作,但 'Roles property'
我想知道如何才能做到这一点。我怀疑为复选框提供的名称/ID 不合适。但是,我只是堆栈。也许我应该采取不同的做法。
感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该看到 Phil Haack 关于 模型绑定到列表。
本质上,您需要的只是提交一堆具有相同名称的表单字段。
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.
我认为问题在于您如何提交表单数据。为了使模型绑定正常工作,它需要键名称及其关联值。基于您的代码的以下代码应该正确绑定:
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: