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

偶尔善良 提交于 2020-08-04 02:27:24

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/9142373/html-checkboxfor-not-checked-even-though-the-model-value-is-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!