我怎样才能绑定复选框在MVC3一个视图模型 [英] How can I bind checkboxes to a viewmodel in mvc3

查看:323
本文介绍了我怎样才能绑定复选框在MVC3一个视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很挣扎环绕此我的头:

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

我有一个的usermodel和UserRoleModel:

I have a UserModel and a 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。

First, I haven't been able to figure out how to use CheckBoxFor from my viewModel. But it does display the checkbox options, so I can live with it. But I am unable to figure out how to determine which checkboxes have been checked when the form is posted. I also seem to have broken the client side validation, I assume because I am using a viewModel.

推荐答案

该CheckBoxFor佣工布尔属性进行操作。所以,你可以定义视图模型:

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

再修改您的视图模型AllRoles属性:

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

和视图,而不是写的foreach 循环使用编辑器的模板:

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

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

和最后定义编辑模板 RoleViewModel 键入将被自动呈现的每个元素的 AllRoles 集合(〜/查看/共享/ EditorTemplates / RoleViewModel.cshtml

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 />

而这一切。里面的动作后,你会得到填充了值 AllRoles 属性。

这篇关于我怎样才能绑定复选框在MVC3一个视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆