在 MVC 中绑定(bind)下拉菜单时,我总是收到此错误:There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key country
.
查看
@Html.DropDownList("country", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Controller
List<Companyregister> coun = new List<Companyregister>();
coun = ds.getcountry();
List<SelectListItem> item8 = new List<SelectListItem>();
foreach( var c in coun )
{
item8.Add(new SelectListItem
{
Text = c.country,
Value = c.countryid.ToString()
});
}
ViewBag.countrydrop = item8;
return View();
我不知道怎么解决。
最佳答案
在你的行动中改变ViewBag.countrydrop = item8
至 ViewBag.country = item8;
在 View 中这样写:
@Html.DropDownList("country",
(IEnumerable<SelectListItem>)ViewBag.country,
"Select country")
其实当你写的时候
@Html.DropDownList("country", (IEnumerable)ViewBag.country, "Select country")
或
Html.DropDownList("country","Select Country)
它查找 IEnumerable<SelectListItem>
在 ViewBag
使用关键字 country,您也可以在这种情况下使用此重载:
@Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown
关于c# - 没有具有关键国家/地区的 'IEnumerable<SelectListItem>' 类型的 ViewData 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26585495/