我遇到了这个DropDownListFor()
的问题我有测试控制器:
model.COUNTRYNAME = "Swizerland";
ViewBag.Selecter = new SelectList(new[]
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "Swizerland", Value = "Swizerland", Selected =true},
new SelectListItem { Text = "Russia", Value = "Russia" },
}, "Text", "Value", model.COUNTRYNAME);
在视图
中@Html.DropDownListFor(x => Model.COUNTRYNAME , (SelectList)ViewBag.Selecter)
DropDownListFor没有选择值,它总是选择第一个值。
有什么问题?
如果我使用DropDownList
@Html.DropDownList("COUNTRYNAME" , (SelectList)ViewBag.Selecter)
它也不起作用。
但如果我使用
@Html.DropDownListFor("AAAAAAA" , (SelectList)ViewBag.Selecter)
它工作正常并选择第二个值!怎么了?我不明白。
由于
答案 0 :(得分:0)
试试这样:
model.COUNTRYNAME = "Swizeland";
ViewBag.Selecter = new[]
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "Swizeland", Value = "Swizeland" },
new SelectListItem { Text = "Russia", Value = "Russia" },
};
return View(model);
并在视图中:
@Html.DropDownListFor(
x => x.COUNTRYNAME,
(IEnumerable<SelectListItem>)ViewBag.Selecter
)
但更好的方法是使用视图模型:
model.SelectedCountry = "Swizeland";
model.Countries = new[]
{
new SelectListItem { Text = "USA", Value = "USA" },
new SelectListItem { Text = "Swizeland", Value = "Swizeland" },
new SelectListItem { Text = "Russia", Value = "Russia" },
};
return View(model);
并在视图中:
@Html.DropDownListFor(x => x.SelectedCountry, Model.Countries)