How to use @Html.CheckBoxFor() while dealing with a List

前端 未结 4 1892
无人及你
无人及你 2020-12-19 12:53

This is my View. How to use CheckboxFor():

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

C

相关标签:
4条回答
  • 2020-12-19 13:36

    If I undestood right, You mean this? And IsEnabled should bool type

    model

    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; }
    }
    

    view

    @foreach (RoleAccessViewModel mnu in Model.RoleAccess)
    {
        @Html.CheckBoxFor(m => mnu.IsEnabled )
    }
    
    0 讨论(0)
  • 2020-12-19 13:36

    I know it is pretty old but

    In your model use DataAnotations Display Attribute

    public class MyModel
       int ID{get; set;};
       [Display(Name = "Last Name")]
       string LastName {get; set;};
    end class
    
    0 讨论(0)
  • 2020-12-19 13:44

    CheckBoxFor works with boolean properties only. So the first thing you need to do is to modify your view model in order to include a boolean property indicating whether the record was selected:

    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; }
    }
    

    and then I would recommend replacing your foreach loop with an editor template:

    <div>
        @Html.EditorFor(x => x.RoleAccess)
    </div>
    

    and finally write the corresponding editor template which will automatically be rendered for each element of the RolesAccess collection (~/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)
    
    0 讨论(0)
  • 2020-12-19 13:50

    Change foreach with 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
    }
    
    0 讨论(0)
提交回复
热议问题