質問

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.

 @Html.CheckBox("abcd",false)

Output:

<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?

役に立ちましたか?

解決

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.

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top