如果在 DropDownListFor() 中使用模型,则缺少所选值
本文关键字:模型 DropDownListFor 如果 | 更新日期: 2023-09-27 18:32:59
我在这个 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 没有选择值,它始终选择第一个值。
怎么了?
如果我使用下拉列表
@Html.DropDownList("COUNTRYNAME" , (SelectList)ViewBag.Selecter)
它也不起作用。
但是如果我使用
@Html.DropDownListFor("AAAAAAA" , (SelectList)ViewBag.Selecter)
它工作正常,选择第二个值!会发生什么?我不明白。
谢谢
尝试如下:
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)