Take the 2-minute tour ×

Possible Duplicate:
ASP.NET MVC:Why does the CheckBoxFor render an additional input tag and how can I get the value using the FormCollection

I needed to create a check box and bind the model to the check box. Assume instead of the model value im just assigning false as the value. Code given bellow.



<input id="abcd" name="abcd" type="checkbox" value="true" />
<input name="abcd" type="hidden" value="false" />

The output of the HTML being generated is shown above. I do understand why the hidden check box is put by the razor view engine. My question is if the value is false then the check box visible should be value="false" (unchecked).

Why it has put value="true" (checked). Same applies for the checkboxfor helper. What is wrong or could you explain how to implement this?

share|improve this question
add comment

marked as duplicate by Øyvind Knobloch-Bråthen, Mark, Robert Koritnik, NULL, Linger Nov 16 '12 at 14:05


2 Answers

up vote 2 down vote accepted

You should consider passing the value via the model:

@Html.CheckBoxFor(model => model.abcd)

If you need to set it to be 'false' then you can do this by setting the abcd property to false in the Controller before returning the View.

share|improve this answer
add comment

Checkboxes don't have different checked/unchecked values, they only have a checked value. If you understand why razor outputs the hidden field then you understand this.

Imagine for a second that it did have value='false'. What would happen when you checked the checkbox? Would you expect the value to change? (hint: you shouldn't). You'd have a checked checkbox with value='false'. What does that even mean? Then, upon posting, you would post false as your value, and that would be nonsense.

So. Checkbox value attributes don't change. If you need to write code that uses the value, don't look for its value, look for whether or not it's checked.

share|improve this answer
So if i need the checkbox to be checked and unchecked based on the true or false that we pass eg @Html.CheckBox("abcd",false) what should i do? Since i couldnt get what i wanted from your answer. –  Desmond Nov 16 '12 at 9:01
@Desmond A checkbox inputs "checked" state is a separate property from its value. Notice that if you check and un-check a textbox the value property does not change, however the browser sees whether the checkbox is checked or not and if it's checked it posts the input name/value, if it's not checked it does not post anything at all. Hence why there's automatically a 2nd hidden input field with value set to false created, so if user checks the checkbox the server will receive two key/value pairs for both inputs, true and false and it will accept true in this case, if one just false. –  LaserBeak Nov 17 '12 at 6:41
add comment
