Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.CheckBoxFor not checked even though the model value is true

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?

like image 760
eliah Avatar asked Feb 04 '12 16:02

eliah


1 Answers

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.

like image 92
Darin Dimitrov Avatar answered Oct 15 '22 20:10

Darin Dimitrov