乍一看,這篇文章可能看起來像重複,但事實並非如此。相信我,我已經看遍了堆棧溢出無濟於事。MVC 5複選框返回「False,false」或「false」
無論如何,我從Html.CheckBoxFor得到一些奇怪的行爲。
我有這個下面定義的屬性視圖模型
[Display(Name = "User is active")]
public bool IsActive { get; set; }
它在Html.BeginForm呈現爲
<div class="form-group">
@Html.LabelFor(model => model.IsActive, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.CheckBoxFor(model => model.IsActive, htmlAttributes: new { @value = Model.IsActive /*Also tried @checked = Model.IsActive*/ })
@Html.ValidationMessageFor(model => model.IsActive)
</div>
</div>
認爲
if (userInfo.isActive != null)
{
//Cast to bool because userInfo.isActive is Nullable<bool>
model.IsActive = (bool)userInfo.isActive;
}
ModelState.Clear();
return View(model);
然後才初始化並返回到控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditProfile(EditProfileViewModel model, string Roles, HttpPostedFileBase ProfileImage)
{
//There's a lot more up here, but it's not relevant to the problem
userInfo.isActive = model.IsActive;
var tmp = Request.Form["IsActive"]; //Added just to check the form value
try
{
db.Entry(userInfo).State = EntityState.Modified;
//Assign changed data to userInfo
db.SaveChanges();
}
}
當model.IsActive被初始化爲true並且我沒有取消選中該複選框時,控制器後期中的model.IsActive值爲true,或者如果我取消選中該複選框,那麼model.IsActive的值會返回作爲虛假的,一切都是瘋狂的。
當model.IsActive被初始化爲false時,會發生該問題。我閱讀了很多堆棧溢出帖子,解釋如果複選框未被選中,則返回「false」,並且如果它被選中「true,false」被返回,但那不是我得到的行爲。當複選框被初始化爲false並且在視圖中檢查時,model.IsActive的值仍然會返回false,並且當我檢查表單元素的值(請參閱控制器後期中的「var tmp」)時,它是「false,false」 。 「真,假」是預期的價值,不是嗎?只有在試圖將模型值從false更改爲true時纔會發生這種情況,不存在從true到false的問題。
So Stack Overflow,發生了什麼?!
只需從@ Html.CheckBoxFor幫手中刪除'@value = Model.IsActive'並且它將正常工作 –
對不起,我應該指定,我也嘗試過不傳入@值,沒有什麼區別。我正在考慮創建一個標準的HTML複選框,並將該值作爲單獨的參數傳遞。 – Francis
亞歷克斯是正確的,從CheckBoxFor中刪除htmlAttributes。在他們內部設置@value正在搞亂CheckBoxFor已經提供給您的綁定,lambda'model => model.IsActive'。 – NigelK