如何在处理List 时使用@ Html.CheckBoxFor()

这是我的观点。 如何使用CheckboxFor():

@using eMCViewModels; @model eMCViewModels.RolesViewModel @{ ViewBag.Title = "CreateNew"; } 

CreateNew

@using (Html.BeginForm()) { @Html.ValidationSummary(true)
RolesViewModel
@Html.LabelFor(model => model.Name)
@Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name)
@foreach (RoleAccessViewModel mnu in Model.RoleAccess) { // How to use checkboxfor here? }

}
@Html.ActionLink("Back to List", "Index")
@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Model.RoleAccess是一个List ,我想使用@Html.CheckBoxFor()创建复选框。

这是我的RoleAccessViewModel

 public class RoleAccessViewModel { public int RoleID { get; set; } public string RoleName { get; set; } public int MenuID { get; set; } public string MenuDisplayName { get; set; } public string MenuDiscription { get; set; } public string IsEnabled { get; set; } // changed to bool } 

假设列表中有5个项目,那么我需要5个带ID = menuID和Text = menuDisplayName的复选框。 我怎样才能做到这一点?

编辑

我的尝试

 @Html.CheckBoxFor(x=>x.RoleAccess.SingleOrDefault(r=>r.MenuID==mnu.MenuID).IsEnabled ) @Html.LabelFor(x=>x.RoleAccess.SingleOrDefault(r=>r.MenuID==mnu.MenuID ).MenuDisplayName ) 

但是在将IsEnabled的类型从string更改为bool 。 该复选框有效。 但Label只打印MenuDisplayName而不是值。 任何人都可以帮忙吗?

改变foreach for for

 @for(int i = 0; i < Model.RoleAccess.Count; i++) { Html.CheckBoxFor(Model.RoleAccess[i].IsEnabled, new { id = Model.RoleAccess[i].MenuID }); Html.DisplayFor(Model.RoleAccess[i].MenuDisplayName); // or just Model.RoleAccess[i].MenuDisplayName } 

如果我感觉不对,你的意思是这个? 并且IsEnabled应该bool类型

模型

 public class RoleAccessViewModel { public int RoleID { get; set; } public string RoleName { get; set; } public int MenuID { get; set; } public string MenuDisplayName { get; set; } public string MenuDiscription { get; set; } public bool IsEnabled { get; set; } } 

视图

 @foreach (RoleAccessViewModel mnu in Model.RoleAccess) { @Html.CheckBoxFor(m => mnu.IsEnabled ) } 

CheckBoxFor仅适用于布尔属性。 因此,您需要做的第一件事是修改视图模型,以便包含一个布尔属性,指示是否选择了记录:

 public class RoleAccessViewModel { public int RoleID { get; set; } public string RoleName { get; set; } public int MenuID { get; set; } public string MenuDisplayName { get; set; } public string MenuDiscription { get; set; } public bool IsEnabled { get; set; } } 

然后我建议用编辑器模板替换你的foreach循环:

 
@Html.EditorFor(x => x.RoleAccess)

最后编写相应的编辑器模板,该模板将自动为RolesAccess集合的每个元素呈现( ~/Views/Shared/EditorTemplates/RoleAccessViewModel.cshtml ):

 @model RoleAccessViewModel @Html.HiddenFor(x => x.RoleID) ... might want to include additional hidden fields ... for the other properties that you want to be bound back @Html.LabelFor(x => x.IsEnabled, Model.RoleName) @Html.CheckBoxFor(x => x.IsEnabled) 

我知道它已经很老了但是

在您的模型中使用DataAnotations显示属性

 public class MyModel int ID{get; set;}; [Display(Name = "Last Name")] string LastName {get; set;}; end class