in asp.net mvc, it seems like checkboxes bind to array of strings (if they are checked). is there any view control that will bind to a boolean in my controller action
public ActionResult Go(bool isBold)
{
}
in asp.net mvc, it seems like checkboxes bind to array of strings (if they are checked). is there any view control that will bind to a boolean in my controller action
public ActionResult Go(bool isBold)
{
}
In your view you can use the Html.CheckBox
helper:
<%= Html.CheckBox("isBold") %>
This will in fact render two HTML input fields:
<input type="checkbox" name="isBold" value="..." />
<input type="hidden" name="isBold" value="false" />
This is why it might appear that "bool" binds to arrays of booleans, which isn't exactly true.
The reason there are two inputs is that checkboxes that are unchecked post no value at all. That means ASP.NET MVC can't tell the difference between "this wasn't posted at all" as opposed to "this was posted but it was not checked."
By having two inputs ASP.NET MVC is guaranteed to always get at least one input. Then it just looks at the first. Here's what happens:
If the checkbox is checked, it sees "true,false" and picks the first value: true
.
If the checkbox is unchecked it sees "false" and picks the first value: false
.
You can still use other helpers with boolean input values, such as Html.TextBox
or Html.DropDownList
. The only thing that ASP.NET MVC cares about is that the first posted value with that name either says "true" or "false".