模型
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();
}
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
为空。
我无法找到解决方案。对此有何建议?为什么只有roleNames发布空...
...谢谢
答案 0 :(得分:1)
这是因为roleName
不是输入字段。只有输入字段会回发到服务器而不是显示字段。
因此,您可以将角色名称存储在像RoleId这样的隐藏字段中,并且您应该能够访问它。
<input type="hidden" id="hdnRoleName" name="hdnRoleName" value="@Model.RoleName" />
在你的行动中
您可以从Request["hdnRoleName"]
或更确切地说从formcollection访问它。
答案 1 :(得分:0)
我发现Html.CheckBoxFor()帮助器中有很多东西以及它是如何工作的。请查看这篇文章:ASP.NET MVC Multiple Checkboxes Validation and Handling using C#