Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ASP.NET MVC Html.CheckBox output two INPUTs with the same name?

Tags:

asp.net-mvc

Why in the world does the line:

<%= Html.CheckBox("ForSale", Model.Product.ForSale)%> For Sale 

result in the following HTML:

<input id="ForSale" name="ForSale" type="checkbox" value="true" /> <input name="ForSale" type="hidden" value="false" /> For Sale 

Now whenever I check the box and access Request.Form["ForSale"], I get the ridiculous answer of "true,false". Am I supposed to parse that?

This hidden field doesn't appear for the other HtmlHelper controls, so why does it for CheckBox?

How do I turn this stupid "feature" off? Or did the HtmlHelper just outgrow its usefulness?

Update

From the answer below, it seems that there is some logic behind this. I have prepared a little extension method so I don't have to think about it (thanks to @eu-ge-ne):

    public static bool GetCheckBoxValue(this System.Web.HttpRequestBase req,                                          string name) {         return Convert.ToBoolean(req.Form.GetValues(name).First());     } 
like image 816
Frank Krueger Avatar asked Jul 14 '09 19:07

Frank Krueger


People also ask

Why is checkbox always true?

Explanation: you were reading the value of the checkbox which is always true, you need to check whether its checked attribute is checked or unchecked. I used the ternary operator to check check whether it's checked or not You could have also used $("#status").is(":checked") but it is slower. Show activity on this post.

How to display CheckBoxes in Html?

The <input type="checkbox"> defines a checkbox. The checkbox is shown as a square box that is ticked (checked) when activated. Checkboxes are used to let a user select one or more options of a limited number of choices. Tip: Always add the <label> tag for best accessibility practices!

Why is HTML checkbox generating an additional hidden input?

CheckBox is generating an additional hidden field with a false value. It is because, when you not select a checkbox, still form sends a false value to the server.


1 Answers

It forces the field to be included if it's unchecked. If you uncheck a check box it doesn't get sent as part of the page - they are only sent if they're checked, and then there's a value of true. The hidden field ensures that false will be send if the check box is unchecked, as the hidden field is always sent.

like image 195
blowdart Avatar answered Sep 30 '22 21:09

blowdart