问题描述
我有一个Razor部分视图,该视图由一个视图模型支持,该视图模型除其他外还包含一个称为UseDuo的布尔值.假设UseDuo属性为true,然后将以下代码放入Razor中:
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 *@
前两个复选框未选中,但第三个复选框已选中,最后一行输出为"UseDuo = true".是什么赋予了?根据我对这些HTML助手的了解,应选中所有三个复选框.但是看来,如果我的复选框的名称与我的模型属性的名称匹配,则拒绝对其进行正确的检查.
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.
我尝试调试.Net MVC源代码,但是调试器拒绝为我提供所涉及的大多数变量的值,因此并没有太大帮助.
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.
刚刚意识到这里没有实际的问题.我的问题:为什么前两个框未选中?
Just realized there's no actual question here. My question: Why aren't the first two boxes checked?
推荐答案
如果@Html.CheckBoxFor(m => m.UseDuo)
呈现未选中的复选框,并且您已验证Model.UseDuo = true
,则唯一可能的原因是已经有一个UseDuo
值与模型冲突的模型状态.为了确保这一点,请尝试在返回视图之前将其删除:
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();
现在,CheckBox帮助器将从模型中选择值.如果选中此复选框,则必须查找在代码的哪一部分中UseDuo
值已插入到模型状态中.
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.
这篇关于Html.CheckBoxFor即使模型值为true也不检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!