楷模
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
空值。
我找不到解决方案。对此有何建议?为什么只有角色名称发布空...
谢谢...