1
我有兩個編輯用戶操作方法。第一個選項用IsAdmin
屬性正確填充複選框。如何在MVC3視圖中從布爾模型屬性重新填充複選框
public ActionResult Edit(string username)
{
var user = Membership.GetUser(username);
var model = Map(user);
return View(model);
}
第二種方法應該檢查是否登錄用戶試圖刪除自己的管理員PRIVS(未選中該複選框),並通過設置model.IsAdmin財產回真正的重新填充的複選框。返回的模型已正確填充,但複選框未被檢查。
[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>
}
完美。謝謝Darin。 – friedX 2012-01-05 09:57:06