如何从的FormCollection获取复选框的价值? [英] How to get checkbox value from FormCollection?

查看:116
本文介绍了如何从的FormCollection获取复选框的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复选框和按钮:

  @using(Html.BeginForm())
{
    < D​​IV ID =搜索块>
        <输入类型=复选框NAME =SHOWALLID =SHOWALL>包含完成
        <输入类型=提交值=应用/>
    < / DIV>
}

和控制器中的第二件事情:

  [HttpPost]
公众的ActionResult指数(的FormCollection集合)
{
    VAR SHOWALL =收集[SHOWALL];
    TempData的[SHOWALL] = SHOWALL;    ...
    某物
    ...
}

它的实际工作,但是:

如果复选框不检查我收到空(不打扰我了)。

如果复选框被选中,我收到上的从的FormCollection,这不是我所需要的我。我需要接受true或false。

我怎样才能做到这一点?


解决方案

 <输入类型=复选框NAME =SHOWALLID =SHOWALL>包含完成

将会在ON后关闭

这不会绑定到一个布尔

要获得你可以使用HTML帮助复选框布尔值

  @ Html.CheckBox(SHOWALL)
<标签=SHOWALL的风格=显示:内联>包含完成< /标签>

更新:


  

如果检查HTML助手将回发真,假,如果
  选上,


您可以有这样的解决方法,因为

 布尔MyBoolValue = Convert.ToBoolean(集合[SHOWALL]斯普利特('')[0]);

这是因为HTML辅助类增加了一个额外隐藏字段保存复选框的状态

I have a checkbox and button:

@using(Html.BeginForm())
{
    <div id="search-block">
        <input type="checkbox" name="showAll" id="showAll">Include completed
        <input type="submit" value="Apply"/>
    </div>
}

and second thing in controller:

[HttpPost]
public ActionResult Index(FormCollection collection)
{
    var showAll = collection["showAll"];
    TempData["showAll"] = showAll;

    ... 
    something
    ...
}

Its actually works, BUT:

If checkbox are not checked I am receiving null (doesn't bother me much).

If checkbox is checked, I am receiving "on" from FormCollection, and this is not what I am needed. I need to receive true or false.

How can I do this?

解决方案

<input type="checkbox" name="showAll" id="showAll">Include completed

Will Post a value of "on" or "off".

This WONT bind to a boolean,

To receive a boolean value you can use HTML Helper Checkbox Like

@Html.CheckBox("showAll")
<label for="showAll" style="display:inline">Include completed</label>

Update:

If checked the html helper will post back "true,false" and if unchecked as "false"

You can have this workaround as

bool MyBoolValue= Convert.ToBoolean(collection["showAll"].Split(',')[0]);

This is because the Html helpers class adds an extra hidden field to save the state of the checkbox

这篇关于如何从的FormCollection获取复选框的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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