Checkbox checked value not set as expected

Possible duplicate:
ASP.NET MVC: Why CheckBoxFor Creates an Extra Input Tag and How Can I Get the Value Using FormCollection

I needed to create a checkbox and bind the model to the checkbox. Assume that instead of the model value im, simply assigning the value false. The code is below.

@Html.CheckBox("abcd",false) 

Output:

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

The result of the generated HTML is shown above. I understand why the hidden checkbox is set by the razor view mechanism. My question is: if false, then the visible flag should be value="false" (unchecked).

Why did he put value="true" (checked). The same goes for checkboxfor helper. What is wrong, or could you explain how to implement this?

+4
source share
2 answers

You should consider passing the value through the model:

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

If you need to set it to false, you can do this by setting the abcd property to false in the controller before returning the view.

+3
source

Flags do not have different marked / unverified values; they have only a verified value. If you understand why a razor displays a hidden field, you understand that.

Imagine that it has value='false' . What happens if you check the box? Do you expect the value to change? (hint: you shouldn't). Check the box with value='false' . What does that even mean? Then, after posting, you will send false as your value, and that would be pointless.

So. Flag attribute values ​​are not changed. If you need to write code that uses this value, do not look at its value, see if it is checked.

+1
source

Source: https://habr.com/ru/post/1446397/


All Articles