How can I bind checkboxes to a viewmodel in mvc3

后端 未结 2 757
天涯浪人
天涯浪人 2021-02-15 03:14

I\'m really struggling to wrap my head around this:

I have a UserModel and a UserRoleModel:

    public class UserModel
{
    [Required]
    [Display(Name         


        
相关标签:
2条回答
  • 2021-02-15 03:25

    The CheckBoxFor helper operates with boolean properties. So you could define a view model:

    public class RoleViewModel
    {
        public string Name { get; set; }
        public bool Selected { get; set; }
    }
    

    and then modify the AllRoles property on your view model:

    public class UserRoleModel
    {
        public IEnumerable<RoleViewModel> AllRoles { get; set; }
        public UserModel user { get; set; }
    
        public UserRoleModel()
        {
            this.AllRoles = Roles.GetAllRoles().Select(r => new RoleViewModel 
            {
                Name = r
            });
            this.user = new UserModel();
        }
    }
    

    and in the view instead of writing foreach loops use an editor template:

    <div class="editor-field">
        @Html.EditorFor(x => x.AllRoles)
    </div>
    

    and finally define an editor template for the RoleViewModel type which will be automatically rendered for each element of the AllRoles collection (~/Views/Shared/EditorTemplates/RoleViewModel.cshtml)

    @model RoleViewModel
    @Html.CheckBoxFor(x => x.Selected)
    @Html.LabelFor(x => x.Selected, Model.Name)
    @Html.HiddenFor(x => x.Name)
    <br />
    

    And that's all. Inside the Post action you will get the AllRoles property populated with the values.

    0 讨论(0)
  • 2021-02-15 03:43

    As Rob mentioned in the previous answer all the Selected properties will be False. I used this piece of code to cover that.

    AllRoles  = Roles.GetAllRoles().Select(r => new RoleViewModel()
    {
         Name = r,
         Selected = Roles.GetRolesForUser(uvm.UserProfile.UserName).Contains(r) ? true : false
    });
    
    0 讨论(0)
提交回复
热议问题