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"]);
Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field.
Just add value="true" to the input tag. And use a hidden with value="false" as shown below.
checkbox1. Attributes. Add("checked","true");
It is used to get multiple inputs from the user. It allows user to select choices from the set of choices. It takes user input in yes or no format. It is useful when we want multiple choices from the user. To create CheckBox we can drag it from the toolbox in visual studio.
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) { ... }
I've recently dealt with this issue and came up with a method of bypassing the MVC binding and using Contains("true") on the query string. Nothing else worked for me.
If people are stuck with the other answers then this is what worked for me - http://websitesorcery.com/post/2012/03/19/CheckBox-Issue-with-MVC-3-WebGrid-Paging-Sorting.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With