MVC3 如何将多个复选框绑定到 ViewModel 中的 1 个属性
我需要显示一个复选框列表,可以选中多个复选框。
当用户点击提交时,这些复选框的值需要进入 ViewModel 中的属性...这是我到目前为止所得到的...
public class RegisterModel
{
public List<string> Roles { get; set; }
public List<RoleModel> SelectedRoles { get; set; }
}
public class RoleModel
{
public string RoleName { get; set; }
}
在视图中我正在尝试执行此操作...
@foreach (var role in Model.Roles)
{
@Html.CheckBoxFor(m => m.SelectedRoles, role.RoleName)@role.RoleName
}
我收到以下错误:
CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool'
谁能告诉我我做错了什么?
I need to display a list of checkboxes, which more than one can be checked.
When the user hits submit, the value of these checkboxes need to go into a property in the ViewModel...this is what I got so far...
public class RegisterModel
{
public List<string> Roles { get; set; }
public List<RoleModel> SelectedRoles { get; set; }
}
public class RoleModel
{
public string RoleName { get; set; }
}
In the view I am trying to do this...
@foreach (var role in Model.Roles)
{
@Html.CheckBoxFor(m => m.SelectedRoles, role.RoleName)@role.RoleName
}
I get the following error:
CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'bool'
Can someone tell me what I'm doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
简单:调整视图模型以满足您的视图要求(即显示某些角色的复选框列表),使用编辑器模板并避免在视图中编写循环。
所以:
视图模型:
控制器:
视图(
~/Views/Home/Index.cshtml
):编辑器模板(
~/Views/Home/EditorTemplates/RoleModel.cshtml
):Simple: adapt your view models to match your views requirement (which is to show a list of checkboxes for some roles), use editor templates and avoid writing loops in your views.
So:
View model:
Controller:
View (
~/Views/Home/Index.cshtml
):Editor template (
~/Views/Home/EditorTemplates/RoleModel.cshtml
):