asp.net-mvc Razor ViewEngine HTML.Checkbox 方法创建一个隐藏的输入。为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5462967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:03:06  来源:igfitidea点击:

Razor ViewEngine HTML.Checkbox method creates a hidden input. Why?

asp.net-mvcasp.net-mvc-3razorcheckbox

提问by tugberk

I have written the below code on my view page;

我已经在我的视图页面上编写了以下代码;

@Html.CheckBox("ChxName",true)

and I got the following result;

我得到了以下结果;

<input checked="checked" id="ChxName" name="ChxName" type="checkbox" value="true" />
<input name="ChxName" type="hidden" value="false" />

why is there a input element named as the same with checkbox?

为什么有一个与复选框名称相同的输入元素?

回答by ericvg

Unchecked checkboxes are not posted, so the hidden field (set as false) allows the model binding to still work.

未选中的复选框不会发布,因此隐藏字段(设置为 false)允许模型绑定仍然有效。

Look at Request.Form on the post back. If the checkbox is checked, you'll see:

查看回帖上的 Request.Form。如果选中该复选框,您将看到:

ChxName=true&ChxName=false

The model binder uses the first value.

模型绑定器使用第一个值。

and, if the box isn't checked, you'll see:

并且,如果未选中该框,您将看到:

ChxName=false

回答by Valamas

ericvg explained it well.

ericvg 解释得很好。

The manual approach is this:

手动方法是这样的:

bool IsDefault = (Request.Form["IsDefault"] != "false");

回答by pfeds

Or use Contains("true") which I find a bit neater...

或者使用我觉得更简洁的 Contains("true") ......

bool myCheckBoxValue = Server.HtmlEncode(Request.QueryString["MyCheckBoxValue"]).Contains("true");