如何从 FormCollection 获取复选框值? [英] How to get checkbox value from FormCollection?
问题描述
我有一个复选框和按钮:
@using(Html.BeginForm()){<div id="搜索块"><input type="checkbox" name="showAll" id="showAll">包含完成<input type="submit" value="Apply"/>
}
和控制器中的第二件事:
[HttpPost]公共 ActionResult 索引(FormCollection 集合){var showAll = collection["showAll"];TempData["showAll"] = showAll;...某物...}
它确实有效,但是:
如果未选中复选框,我将收到 null(我不会太在意).
如果复选框被选中,我会收到来自 FormCollection
的on",这不是我需要的.我想收到真假.
我该怎么做?
Include completed
将发布 "on"
或 "off"
的值.
这个不会绑定到一个布尔值,
要接收布尔值,您可以使用 HTML Helper Checkbox喜欢
@Html.CheckBox("showAll")<label for="showAll" style="display:inline">包括已完成</label>
更新:
<块引用>如果选中,html helper 将回发 "true,false"
并且如果未选中为 "false"
您可以将此解决方法作为
bool MyBoolValue= Convert.ToBoolean(collection["showAll"].Split(',')[0]);
这是因为Html helpers 类添加了一个额外的hidden
字段来保存复选框的状态
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
...
}
It's actually working, BUT:
If checkboxes are not checked, I am receiving null (doesn't bother me much).
If checkboxes are checked, I am receiving "on" from FormCollection
, and this is not what I need. I want 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屋!