DropDownListFor(...)默认情况下选择布尔值false [英] DropDownListFor(...) selecting boolean false by default
问题描述
我在应用程序中有典型的YesNo下拉列表.为此,我为将来的扩展开发了模型(而不是ViewModel Utility)类.
I have typical YesNo kind of dropdown in the application. For that, I have developed model (rather ViewModel Utility) class for future extension prupose.
public string Text { get; set; } // represents text part
public bool Value { get; set; } // represent value
public List<DropDown> DropDowns { get; set; } //list for binding
public void BuildYesNoDropDown()
{
DropDowns = new List<DropDown>();
DropDowns.Add(new DropDown { Text = "Yes", Value = true });
DropDowns.Add(new DropDown { Text = "No", Value = false });
}
然后,将其绑定在如下视图中:
Then, I bind it in view like following:
@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.DropDowns, "Value", "Text",1),"Select") //last para - OptionLabel
在视图上,所有三个参数都将显示,即选择",是"和否".但是,默认情况下已选择否".如果我将值"属性设置为整数,则可以正常工作,并且默认情况下会选择选择",但是如代码中所述,如果我倾向于使用布尔类型,则会选择否".
On the view, all three parameters are getting display i.e. "Select", "Yes" and "No". But, by default "No" has been selected. If I make "Value" property as integer then it works fine and by default "Select" gets selected, but as mentioned in the code, if I tend to go with bool type then "No" gets selected.
当DataValueField为bool时如何获得正常行为?
How to get normal behavior when DataValueField is bool?
推荐答案
型号:
public bool? Value { get; set; }
查看:
@Html.EditorFor(model => model.Value)
这会自动创建一个下拉列表,其中包含3个与可空布尔的3个状态相匹配的状态:null,true,false.如果您需要回答值",则可以使用如下数据注释:
This makes a drop down list automatically with 3 states that match the 3 states of a nullable bool: null, true, false. If you require that Value be answered you can use data annotations like so:
型号:
[Required]
public bool? Value { get; set; }
要点是,您的模型需要是一个真实的模型-它需要对未设置到设置的输入值进行建模.如果需要输入int
,则可能需要使用可为null的int(即int?
)并需要该值.这样,初始值将为null而不是0.它与其他数据类型类似,除了string
已经可以为空.
The takeaway is your model needs to be a real model -- it needs to model the input values from unset to set. If you need to input a int
, you'll likely want to use a nullable int (so int?
) and require the value. That way the initial value is null instead of 0. It is similar with other data types except string
which is already nullable.
这篇关于DropDownListFor(...)默认情况下选择布尔值false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!