加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – MVC @ Html.CheckboxFor在表单提交时提交true,fa

发布时间:2020-12-16 06:50:24 所属栏目:asp.Net 来源:网络整理
导读:我正在使用MVC 5和EF Code First,并且有一个包含bool的View模型: public bool MyCheckbox { get; set; } 我在View的get中初始化了这个: model.MyCheckbox = true; 在视图中: @Html.CheckBoxFor(m = m.MyCheckbox) 其中呈现为: input checked="checked" d
我正在使用MVC 5和EF Code First,并且有一个包含bool的View模型:

public bool MyCheckbox { get; set; }

我在View的get中初始化了这个:

model.MyCheckbox = true;

在视图中:

@Html.CheckBoxFor(m => m.MyCheckbox)

其中呈现为:

<input checked="checked" data-val="true" data-val-required="The field is required." id="MyCheckbox" name="MyCheckbox" type="checkbox" value="true" />
<input name="MyCheckbox" type="hidden" value="false" />

我在View上的一个按钮触发了一个Ajax POST到Controller,我想查看复选框值:

bool bValue = Request["MyCheckbox"] == "true";

但是由于名称=“MyCheckbox”的额外隐藏字段,Request [“MyCheckbox”]的值为“true,false”.

如何使用Request [“…”]查看控制器中此复选框的值并理解它(是真还是假)?

我在View模型中还有另一个bool成员,我故意在隐藏字段中使用它.在模型中:

bool MyHiddenBool { get; set; }

在Controller获取:

model.MyHiddenBool = true;

在视图中:

@Html.HiddenFor(x => x.MyHiddenBool)

在Controller中(通过Ajax POST):

bool AnotherBool = Request["MyHiddenBool"] == "true";

但Request [“MyHiddenBool”]的值是“True”或“False”而不是“true”和“false”.

是什么给出了这种不一致性,如何在我的视图中可靠地看到这两种bool方法的值?

解决方法

问题是你如何使用表单请求变量.

在ASP.NET MVC中,可能永远不会有充分的理由使用Request.Form或它的变体来使用您的请求数据.您需要创建模型或为操作添加参数.

[HttpPost]
public ActionResult PostedForm(bool myHiddenBool)
{
  //Frameworks model binder will extract the form field into your variable based on the name
}

以下从this answer.复制

This isn’t a bug,and is in fact the same approach that both Ruby on
Rails and MonoRail use.

When you submit a form with a checkbox,the value is only posted if
the checkbox is checked. So,if you leave the checkbox unchecked then
nothing will be sent to the server when in many situations you would
want false to be sent instead. As the hidden input has the same name
as the checkbox,then if the checkbox is unchecked you’ll still get a
‘false’ sent to the server.

When the checkbox is checked,the ModelBinder will automatically take
care of extracting the ‘true’ from the ‘true,false’

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读