我的 View 中有这个下拉列表,我正在尝试连接到我的 MVC4 Web 应用程序中的模型。
这是我的模型对象的一个属性:
/// <summary>
/// Used to provide values in the type drop down list in.
/// </summary>
public IEnumerable<SelectListItem> SomeTypes
{
get
{
var someTypeNames = new [] { "abc", "def", "xyz" };
var someTypes = Enum.GetValues(typeof(ESomeType)).Cast<EsomeType>();
var someTypesSelectItemsList = new List<SelectListItem>();
someTypesSelectItemsList.Add(new SelectListItem()
{
Selected = true,
Text = "Choose a type",
Value = "-1"
});
foreach (var eSomeType in someTypes)
{
var sli = new SelectListItem()
{
Selected = false,
Text = someTypeNames[(int)eSomeType],
Value = ((int)eSomeType).ToString()
};
someTypesSelectItemsList.Add(sli);
}
return someTypesSelectItemsList;
}
set { }
}
这是模型属性,稍后我将在 View 中绑定(bind)下拉列表:
[DataMember, Required]
[Display(Name = "Type:")]
public virtual int SomeType { get; set; }
然后我在我的 View 中打印此内容:
@Html.LabelFor(m => m.SomeType)
@Html.DropDownListFor(m => m.SomeType, new SelectList(Model.SomeTypes, "Value", "Text"), new { ng_model = "type", ng_change = "ChangeType()" })
@Html.ValidationMessageFor(m => m.SomeType)
现在这一切都工作正常(我稍后会重构更多),但我的问题是渲染的 html:
<label for="SomeType">Type:</label>
<select data-val="true" data-val-number="The field Type: must be a number." data-val-required="The Type: field is required." id="SomeType" name="SomeType" ng-change="ChangeType()" ng-model="type">
<option value="-1">Choose a type</option>
<option selected="selected" value="0">abc</option>
<option value="1">def</option>
<option value="2">xyz</option>
</select>
<span class="field-validation-valid" data-valmsg-for="SomeTypeType" data-valmsg-replace="true"></span>
正如您所看到的,“abc”选项被选中=“selected”,而不是我的“选择一种类型”选项,我们可以清楚地看到我的模型中的代码将正确的选项设置为选中。这是怎么回事?
感谢您的帮助!!
最佳答案
当模型绑定(bind)变量与选择列表同名时,就会出现此问题。
尝试将 SelectList
的名称更改为 SomeTypesList
在你的模型中:
public IEnumerable<SelectListItem> SomeTypesList
在您的 View 中:
@Html.DropDownListFor(m => m.SomeType,
new SelectList(Model.SomeTypesList, "Value", "Text"),
new { ng_model = "type", ng_change = "ChangeType()" },
"Choose a type"}
后续说明:您正在选择列表中设置默认值,而不是在助手中设置默认值
关于asp.net - 如何通过@Html.DropDownListFor正确设置选定状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15034712/