DropdownSelected项在DropDownList中工作,但不在DropDownListFor-MVC中
本文关键字:DropDownListFor-MVC 工作 项在 DropDownList DropdownSelected | 更新日期: 2023-09-27 18:28:21
我无法确定DropDownListFor没有选择正确选项的原因。下面是我的代码,我有硬编码的"选定"值进行测试,但当页面加载时,我仍然得到"选择国家/地区"作为选定值。
@Html.DropDownListFor(x => x.CountryID,
new List<SelectListItem> {
new SelectListItem { Text = "USA", Value = "US", Selected = false},
new SelectListItem { Text = "UK", Value = "UK", Selected = true},
new SelectListItem { Text = "Australia", Value = "AUS", Selected = false }
},"Select Country")
但是,DropDownList同样适用!
@Html.DropDownList("CountryID",
new List<SelectListItem> {
new SelectListItem { Text = "USA", Value = "US", Selected = false},
new SelectListItem { Text = "UK", Value = "UK", Selected = true},
new SelectListItem { Text = "Australia", Value = "AUS", Selected = false }
},"Select Country")
请帮忙。
使用强类型辅助对象时,所选选项将基于属性CountryID
的实际值。因此,如果在将模型传递到视图之前在控制器中设置CountryID="UK"
,则会选择第二个选项。
尝试以下操作:
@{
var listItems = new List<SelectListItem>
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "UK", Value = "UK", Selected = true },
new SelectListItem { Text = "Australia", Value = "AUS" }
};
}
@Html.DropDownListFor(x => x.CountryID, listItems, "-- Select Country --")