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

标签 c# asp.net-mvc asp.net-mvc-4

在 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/

相关文章:

c# - 第二次点击后页面刷新吗?

c# - 不可调用成员 'File' 在生成报告时不能像方法一样使用

asp.net-mvc-3 - 自定义正则表达式属性缺少用于客户端验证的 data-val-regex-pattern

c# - 为什么派生 List<T> 类只是为了重申索引器?

c# - 如何使用LINQ实现Left Excluding JOIN?

c# - 模型绑定(bind)自定义类型

asp.net - 2. 如何处理 WebAPI 方法中的异常?

javascript - MVC 根据之前的下拉菜单过滤下拉菜单,重用代码

sql-server - 分布式二级缓存与专注于调优数据库相比有何优缺点

validation - 电子邮件数据注释验证有效,但Phone无效