问题描述
在我的ASP.NET MVC应用程序,我用下面的code渲染一个复选框:
In my ASP.NET MVC app, I am rendering a checkbox using the following code:
<%= Html.CheckBoxFor(i=>i.ReceiveRSVPNotifications) %>
现在,我明白了,这使的两个的复选框输入标签和一个隐藏的输入标签。那我遇到的问题是,当我尝试使用的FormCollection检索复选框的值:
Now, I see that this renders both the checkbox input tag and a hidden input tag. The problem that I am having is when I try retrieve the value from the checkbox using the FormCollection:
FormValues["ReceiveRSVPNotifications"]
我得到的值真,假。当在呈现的HTML看,我可以看到以下内容:
I get the value "true,false". When looking at the rendered HTML, I can see the following:
<input id="ReceiveRSVPNotifications" name="ReceiveRSVPNotifications" value="true" type="checkbox">
<input name="ReceiveRSVPNotifications" value="false" type="hidden">
所以FormValues收集似乎因为它们具有相同的名称加入这两个值。
So the FormValues collection seems to join these two values since they have the same name.
任何想法?
推荐答案
看看这里:
这是不是一个错误,实际上是在同样的做法,这两个的Ruby on
Rails和单轨使用。
当您提交表单一个复选框,该值仅当发布
复选框被选中。所以,如果你离开,然后复选框取消选中
没有什么会在许多情况下被发送到服务器时将
要假,而不是被发送。作为隐藏的输入具有相同的名称
作为复选框,然后如果该复选框被选中,你仍然会得到一个
假发送到服务器
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.
在该复选框被选中,ModelBinder的将自动
将心比心提取真实的真,假
When the checkbox is checked, the ModelBinder will automatically take care of extracting the 'true' from the 'true,false'
这篇关于为什么CheckBoxFor呈现一个额外的输入标签,我怎样才能得到使用的FormCollection的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!