为什么Html.Checkbox(QUOT;可见")返回"真,假"在ASP.NET MVC 2? [英] Why Html.Checkbox("Visible") returns "true, false" in ASP.NET MVC 2?

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

问题描述

我用 Html.Checkbox(可见)显示复选框用户。在后背部,的FormCollection [可见] 值是真,假。为什么呢?

在视图:

 < TD>
    <%:Html.CheckBox(可见)%>
< / TD>

在控制器:

  adslService.Visible = bool.Parse(集合[可见]);


解决方案

这是因为复选框帮助生成具有相同名称的复选框,一个额外的隐藏字段(你可以看到它通过浏览生成的源$ C ​​$ C):

 <输入检查=选中ID =可见NAME =可见类型=复选框VALUE =真/>
<输入名称=可见类型=隐藏值=FALSE/>

所以,当你提交表单两个值发送到控制器动作。在这里,从ASP.NET MVC源$ C ​​$ C解释这背后更多隐藏字段推理的评论直接:

 如果(inputType下== InputType.CheckBox){
    //渲染额外<输入类型=隐藏... />对于复选框。这个
    //地址在哪里选中复选框未在请求中发送的情况。
    //发送一个隐藏的输入,能够知道的复选框是present
    //当请求提交页面上。
    ...

而不是使用的FormCollection 我会用视图模型作为操作参数或直接标量类型建议你,离开解析到默认的模型绑定的麻烦:

 公众的ActionResult SomeAction(布尔可见)
{
    ...
}

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

in view:

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

in controller:

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

解决方案

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" />

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.
    ...

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(QUOT;可见&QUOT;)返回&QUOT;真,假&QUOT;在ASP.NET MVC 2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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