本文介绍了为什么 CheckBoxFor 会呈现额外的输入标签,以及如何使用 FormCollection 获取值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 ASP.NET MVC 应用程序中,我使用以下代码呈现一个复选框:

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.

有什么想法吗?

推荐答案

看看这里:

http://forums.asp.net/t/1314753.aspx

这不是错误,实际上与 Ruby onRails 和 MonoRail 使用.

当您提交带有复选框的表单时,仅在以下情况下才会发布该值复选框被选中.因此,如果您不选中复选框,则在许多情况下,您不会将任何内容发送到服务器希望改为发送 false.由于隐藏输入具有相同的名称作为复选框,那么如果未选中该复选框,您仍然会得到'false' 发送到服务器.

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 获取值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:13
查看更多