为什么ASP.NET MVC Html.CheckBox输出两个名称相同的投入? [英] Why does ASP.NET MVC Html.CheckBox output two INPUTs with the same name?
问题描述
为什么在世界上确实行:
<%= Html.CheckBox(ForSale,Model.Product.ForSale)%GT;出售
结果下面的HTML:
<输入ID =ForSaleNAME =ForSale类型=复选框VALUE =真/>
<输入名称=ForSale类型=隐藏值=FALSE/>
出售
现在,每当我检查框和访问的Request.Form [ForSale]
,我得到的答案可笑真,假
。我应该解析?
这个隐藏字段不会出现其他的HtmlHelper控制,那么,为什么它的CheckBox?
我如何把这个愚蠢的功能了吗?或做了的HtmlHelper
只是长大了它的用处?
更新
从下面的答案,似乎是有这背后一定道理。我有prepared一点点扩展方法,所以我没有去想它(感谢@ EU-GE-NE):
公共静态布尔GetCheckBoxValue(这System.Web.Htt prequestBase REQ,
字符串名称){
返回Convert.ToBoolean(req.Form.GetValues(名称)。首先());
}
这迫使它是否被选中要包含的字段。如果取消选中复选框它不会被作为页面的一部分 - 他们只派,如果他们检查,然后有一个真值。隐藏字段确保false将如果未选中此复选框,可以发送作为隐藏字段总是被发送。
Why in the world does the line:
<%= Html.CheckBox("ForSale", Model.Product.ForSale)%> For Sale
result in the following HTML:
<input id="ForSale" name="ForSale" type="checkbox" value="true" />
<input name="ForSale" type="hidden" value="false" />
For Sale
Now whenever I check the box and access Request.Form["ForSale"]
, I get the ridiculous answer of "true,false"
. Am I supposed to parse that?
This hidden field doesn't appear for the other HtmlHelper controls, so why does it for CheckBox?
How do I turn this stupid "feature" off? Or did the HtmlHelper
just outgrow its usefulness?
Update
From the answer below, it seems that there is some logic behind this. I have prepared a little extension method so I don't have to think about it (thanks to @eu-ge-ne):
public static bool GetCheckBoxValue(this System.Web.HttpRequestBase req,
string name) {
return Convert.ToBoolean(req.Form.GetValues(name).First());
}
It forces the field to be included if it's unchecked. If you uncheck a check box it doesn't get sent as part of the page - they are only sent if they're checked, and then there's a value of true. The hidden field ensures that false will be send if the check box is unchecked, as the hidden field is always sent.
这篇关于为什么ASP.NET MVC Html.CheckBox输出两个名称相同的投入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!