我有两个Edit User Action方法。第一个使用IsAdmin
属性正确填充复选框。
public ActionResult Edit(string username)
{
var user = Membership.GetUser(username);
var model = Map(user);
return View(model);
}
第二种方法应检查登录用户是否已尝试删除自己的管理员权限(取消选中该复选框),并通过将model.IsAdmin属性设置为true来重新填充该复选框。返回的模型已正确填充,但未选中复选框。
[HttpPost]
public ActionResult Edit(UserModel model)
{
if (model.UserName == User.Identity.Name && model.IsAdmin == false)
{
ModelState.AddModelError("", "You cannot remove your own admin privileges");
model.IsAdmin = true;
return View(model);
}
if (ModelState.IsValid)
{
//...
}
}
“编辑用户”视图如下所示
<div class="simpleform">
@using (Html.BeginForm())
{
<fieldset>
<div>
@Html.LabelFor(u => u.UserName)</div>
<div>
@Html.TextBoxFor(u => u.UserName)</div>
<div>
@Html.LabelFor(u => u.IsAdmin)</div>
<div>
@Html.CheckBoxFor(u => u.IsAdmin)</div>
<br />
<div>
<input type="submit" value="Submit" />
@Html.ActionLink("Cancel", "Index")</div>
</fieldset>
}
答案 0 :(得分:1)
在尝试修改之前从modelstate中删除值,否则CheckBoxFor帮助器将使用modelstate中的值而不是视图模型中的值:
if (model.UserName == User.Identity.Name && model.IsAdmin == false)
{
ModelState.AddModelError("", "You cannot remove your own admin privileges");
ModelState.Remove("IsAdmin");
model.IsAdmin = true;
return View(model);
}