如何将复选框绑定到mvc3中的viewmodel

时间:2011-12-22 22:02:00

标签: asp.net-mvc-3

我真的很想绕过这个:

我有一个UserModel和一个UserRoleModel:

    public class UserModel
{
    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    [Display(Name = "Email address")]
    public string Email { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

    public IEnumerable<string> UserRoles { get; set; }
}
public class UserRoleModel
{
    public IEnumerable<string> AllRoles { get; set; }
    public UserModel user { get; set; }

    public UserRoleModel()
    {
        this.AllRoles = Roles.GetAllRoles();
        this.user = new UserModel();
    }
}

在控制器中:

        public ActionResult Create()
    {
        return View(new UserRoleModel());
    }

    [HttpPost]
    public ActionResult Create(UserRoleModel model)
    {
        if (ModelState.IsValid)
        {
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.user.UserName, model.user.Password, model.user.Email, null, null, true, null, out createStatus);

            if (createStatus == MembershipCreateStatus.Success)
            {
                foreach (var r in model.AllRoles)
                {
                    Roles.AddUserToRole(model.user.UserName, r);
                }

                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
        }

        return View(model);
    }

观点:

@model BBmvc.Areas.Tools.Models.UserRoleModel

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>UserModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.user.UserName)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.user.UserName)
        @Html.ValidationMessageFor(model => model.user.UserName)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.user.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.user.Email)
        @Html.ValidationMessageFor(model => model.user.Email)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.user.Password)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.user.Password)
        @Html.ValidationMessageFor(model => model.user.Password)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.user.ConfirmPassword)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.user.ConfirmPassword)
        @Html.ValidationMessageFor(model => model.user.ConfirmPassword)
    </div>
    <div class="editor-field">
        @foreach (var r in @Model.AllRoles)
        {
            @Html.CheckBox(r,false)
            @Html.Label(r)
            <br />
        }
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>

}

首先,我无法弄清楚如何从我的viewModel中使用CheckBoxFor。但它确实显示了复选框选项,因此我可以忍受它。但我无法弄清楚如何确定在发布表单时检查了哪些复选框。我似乎也打破了客户端验证,我假设因为我使用的是viewModel。

2 个答案:

答案 0 :(得分:13)

CheckBoxFor助手使用布尔属性进行操作。所以你可以定义一个视图模型:

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

然后修改视图模型上的AllRoles属性:

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

并且在视图中而不是编写foreach循环使用编辑器模板:

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

最后定义RoleViewModel类型的编辑器模板,该模板将自动为AllRoles集合的每个元素呈现(~/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 />

就是这样。在Post操作中,您将获得填充了值的AllRoles属性。

答案 1 :(得分:0)

正如Rob在上一个回答中提到的,所有Selected属性都是False。 我用这段代码来解决这个问题。

AllRoles  = Roles.GetAllRoles().Select(r => new RoleViewModel()
{
     Name = r,
     Selected = Roles.GetRolesForUser(uvm.UserProfile.UserName).Contains(r) ? true : false
});