为什么 Html.Checkbox(“Visible") 返回“true, false"?在 ASP.NET MVC 2 中? [英] Why Html.Checkbox("Visible") returns "true, false" in ASP.NET MVC 2?

查看:25
本文介绍了为什么 Html.Checkbox(“Visible") 返回“true, false"?在 ASP.NET MVC 2 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Html.Checkbox("Visible") 向用户显示复选框.在回发中,FormCollection["Visible"] 值为true, false".为什么?

I'm using Html.Checkbox("Visible") for displaying a check box to user. In post back, FormCollection["Visible"] value is "true, false". Why?

在视图中:

<td>                
    <%: Html.CheckBox("Visible") %>
</td>

在控制器中:

 adslService.Visible = bool.Parse(collection["Visible"]);

推荐答案

那是因为 CheckBox 助手生成了一个与复选框同名的附加隐藏字段(您可以通过浏览生成的源代码):

That's because the CheckBox helper generates an additional hidden field with the same name as the checkbox (you can see it by browsing the generated source code):

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

因此,当您提交表单时,两个值都会发送到控制器操作.以下是直接来自 ASP.NET MVC 源代码的注释,解释了此附加隐藏字段背后的原因:

So both values are sent to the controller action when you submit the form. Here's a comment directly from the ASP.NET MVC source code explaining the reasoning behind this additional hidden field:

if (inputType == InputType.CheckBox) {
    // Render an additional <input type="hidden".../> for checkboxes. This
    // addresses scenarios where unchecked checkboxes are not sent in the request.
    // Sending a hidden input makes it possible to know that the checkbox was present
    // on the page when the request was submitted.
    ...

我建议您使用视图模型作为动作参数或直接使用标量类型,而不是使用 FormCollection,并将解析的麻烦留给默认模型绑定器:

Instead of using FormCollection I would recommend you using view models as action parameters or directly scalar types and leave the hassle of parsing to the default model binder:

public ActionResult SomeAction(bool visible)
{
    ...
}

这篇关于为什么 Html.Checkbox(“Visible") 返回“true, false"?在 ASP.NET MVC 2 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆