gpt4 book ai didi

c# - 没有具有关键国家/地区的 'IEnumerable' 类型的 ViewData 项目

转载 作者:可可西里 更新时间:2023-11-01 03:06:00 26 4
gpt4 key购买 nike

在 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 = item8ViewBag.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

参见 Working DEMO Example

关于c# - 没有具有关键国家/地区的 'IEnumerable<SelectListItem>' 类型的 ViewData 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26585495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com