2012-01-04 40 views
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> 
} 

回答

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); 
} 
+0

完美。謝謝Darin。 – friedX 2012-01-05 09:57:06