0

楷模

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发布了空值。我的意思是,我调试了它,IsInRole并且RoleId是预期的,但只有roleNames空值。

我找不到解决方案。对此有何建议?为什么只有角色名称发布空...

谢谢...

4

2 回答 2

1

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

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

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

在您的操作中,您可以Request["hdnRoleName"]从 formcollection 或更确切地说从 formcollection 访问它。

于 2013-05-20T20:44:20.273 回答
0

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

于 2013-07-03T10:39:35.267 回答