I've got a Razor partial view backed by a viewmodel containing, among other things, a bool called UseDuo. Let's say the UseDuo property is true, and I put the following code in my Razor:
@Html.CheckBox("UseDuo", Model.UseDuo) @* Not checked *@
@Html.CheckBoxFor(m => m.UseDuo) @* Not checked *@
@Html.CheckBox("UseDuo2", Model.UseDuo) @* checked *@
@(Model.UseDuo ? "UseDuo=true" : "UseDuo=false") @* outputs UseDuo=true *@
The first two checkboxes come out not checked, but the third one is checked, and the last line outputs as "UseDuo=true". What gives? According to my understanding of these Html helpers, all three checkboxes should be checked. But it seems that if the name of my checkbox matches the name of my model property, it refuses to be checked properly.
I tried debugging into the .Net MVC sources, but the debugger refused to give me values for most of the variables invovled, so that wasn't much help.
Edit: Just realized there's no actual question here. My question: Why aren't the first two boxes checked?
If @Html.CheckBoxFor(m => m.UseDuo)
renders a non-checked checkbox and you have verified that Model.UseDuo = true
then the only possible reason is that there is already a UseDuo
value in the modelstate that conflicts with your model. To ensure this try removing it before returning the view:
ModelState.Remove("UseDuo");
Or to entire clear the modelstate:
ModelState.Clear();
Now the CheckBox helper will pick the value from your model. If the checkbox is checked you will have to find in what part of your code the UseDuo
value has been inserted into the modelstate.
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