Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Html.Checkbox("Visible") returns "true, false" in ASP.NET MVC 2?

Tags:

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"]); 
like image 450
Jalal Avatar asked May 09 '11 11:05

Jalal


People also ask

What does HTML CheckBox return?

Return Value: It returns a string value which represent the value of the value attribute of a input checkbox field.

How can get CheckBox value in ASP NET MVC?

Just add value="true" to the input tag. And use a hidden with value="false" as shown below.

How check CheckBox is checked or not in asp net?

checkbox1. Attributes. Add("checked","true");

What is CheckBox control in asp net?

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.


2 Answers

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) {     ... } 
like image 97
Darin Dimitrov Avatar answered Oct 05 '22 21:10

Darin Dimitrov


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

like image 41
pfeds Avatar answered Oct 05 '22 23:10

pfeds