乍一看这篇文章可能看起来像重复,但事实并非如此.相信我,我已经遍布Stack Overflow无济于事.
无论如何,我从Html.CheckBoxFor得到了一些奇怪的行为.
[display(Name = "User is active")] public bool IsActive { get; set; }
它在视图之前初始化
if (userInfo.isActive != null) { //Cast to bool because userInfo.isActive is Nullable<bool> model.IsActive = (bool)userInfo.isActive; } ModelState.Clear(); return View(model);
然后在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>
并返回控制器
[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的值将返回false,并且一切都是没说的.
当model.IsActive初始化为false时,会发生此问题.我阅读了很多Stack Overflow帖子,解释如果未选中该复选框,则返回“false”,如果选中,则返回“true,false”,但这不是我得到的行为.当复选框初始化为false并且我在视图中检查它时,model.IsActive的值仍然返回false,当我检查表单元素的值时(参见控制器帖子中的“var tmp”),它是“false,false” . “真,假”是预期值,不是吗?只有在尝试将模型值从false更改为true时才会发生这种情况,没有问题从true变为false.
那么Stack Overflow,到底发生了什么?!
解决方法
您无需更改复选框的value属性.如果你使用没有它的助手,你会看到
@Html.CheckBoxFor(model => model.IsActive)
被渲染到
<input data-val="true" data-val-required="The IsActive field is required." id="IsActive" name="IsActive" type="checkBox" value="true" class="valid">
您可以看到,虽然Model.IsActive设置为false,但输入的value属性仍然为true
顺便说一下,如果你查看CheckBox助手的源代码,你会发现value = true在那里是硬编码的(所以你不应该改变它):
private static MvcHtmlString CheckBoxHelper(HtmlHelper htmlHelper,ModelMetadata Metadata,string name,bool? isChecked,IDictionary<string,object> htmlAttributes) { RouteValueDictionary attributes = ToRouteValueDictionary(htmlAttributes); bool explicitValue = isChecked.HasValue; if (explicitValue) { attributes.Remove("checked"); // Explicit value must override dictionary } return InputHelper(htmlHelper,InputType.CheckBox,Metadata,name,value: "true",useViewData: !explicitValue,isChecked: isChecked ?? false,setId: true,isExplicitValue: false,format: null,htmlAttributes: attributes); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。