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()); }
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.
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!
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.
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.
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