【问题标题】:ASP.NET MVC Multiple check boxASP.NET MVC 多个复选框
【发布时间】:2013-05-15 12:17:34
【问题描述】:

型号

public class UserRoleViewModel
{
    public UserRoleViewModel()
    {
        Roles = new List<RoleViewModel>();
    }
    public string UserId { get; set; }
    public List<RoleViewModel> Roles { get; set; }
}

public class RoleViewModel
{
    public bool IsInRole { get; set; }
    [HiddenInput(DisplayValue = false)]
    public int RoleId { get; set; }
    [HiddenInput(DisplayValue = true)]
    public string RoleName { get; set; }
}

控制器

public ActionResult EditUserRole(string userId)
{
    var user = userService.GetUser(userId);
    var roles = userService.GetRoles();

    UserRoleViewModel viewModel = new UserRoleViewModel();
    viewModel.UserId = user.UserId;
    //Match the roles the user is in with the list of roles
    foreach (var role in roles)
    {
        viewModel.Roles.Add(new RoleViewModel
                            {
                                IsInRole = user.Roles.Any(r => r.RoleId == role.RoleId),
                                RoleId = role.RoleId,
                                RoleName = role.RoleName
                            });
    }

    return View(viewModel);
}

[HttpPost]
public ActionResult EditUserRole(UserRoleViewModel model)
{
    List<Role> roles = model.Roles.Where(r => r.IsInRole).Select(r => new Role {RoleId = r.RoleId, RoleName = r.RoleName}).ToList();
    userService.AddRolesToUser(model.UserId, roles);

    return View();            
}

查看(EditRole.cshtml)

@model WebUI.ViewModel.UserRoleViewModel

@using (Html.BeginForm("EditUserRole", "Administrator"))
{
    @Html.HiddenFor(x => Model.UserId)

    @Html.EditorFor(x => Model.Roles)

    <input type="submit" />
}

和编辑器模板

@model WebUI.ViewModel.RoleViewModel

@Html.CheckBoxFor(m => m.IsInRole, new { onclick="this.form.submit();"})
@Html.HiddenFor(m => m.RoleId)
@Html.LabelFor(m => m.IsInRole, Model.RoleName)
<br />

编辑器模板中的重要行(我添加了 onclick 事件):

@Html.CheckBoxFor(m => m.IsInRole, new { onclick="this.form.submit();"})

一切都很好,但只有roleNames 以空值发布。我的意思是,我对其进行了调试,预计 IsInRoleRoleId,但只有 roleNames 为空。

我找不到解决方案。对此有何建议?为什么只有 roleNames 发布 null...

谢谢...

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 checkbox onclick


    【解决方案1】:

    这是因为roleName 不是输入字段。只有输入字段被发送回服务器,而不是显示字段。

    因此,您可以将角色名称存储在 RoleId 等隐藏字段中,并且您应该能够访问它。

    <input type="hidden" id="hdnRoleName" name="hdnRoleName" value="@Model.RoleName" />
    

    在你的行动中 您可以从 Request["hdnRoleName"] 或 formcollection 访问它。

    【讨论】:

      【解决方案2】:

      我发现 Html.CheckBoxFor() 帮助器中有很多东西以及它是如何工作的。请检查这个帖子:ASP.NET MVC Multiple Checkboxes Validation and Handling using C#

      【讨论】:

        猜你喜欢
        • 2010-12-20
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        • 2011-01-05
        • 2011-08-03
        • 1970-01-01
        • 2012-12-12
        相关资源
        最近更新 更多