2014-10-27 53 views
12

绑定在mvc下拉我总是得到这个错误没有ViewData项目类型'IEnumerable'国家有关键我不知道如何对它进行排序没有类型'IEnumerable <SelectListItem>'的ViewData项目,其关键国家

查看

@Html.DropDownList("country", 
    (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country") 

控制器

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(); 

我不知道我错了,谁能帮助我在此先感谢

+0

我已更新我的代码检查它。 – 2014-10-27 11:07:26

+3

如果你得到这个错误,那么它意味着'ViewBag.coutrydrop'的值是'null'。填充它的代码没有被执行,或者只有当你回发并返回视图时(并且你还没有再次填充'ViewBag.countrydrop') – 2014-10-27 11:08:15

+1

并考虑简化你的代码到'ViewBag.countrydrop = new SelectList(coun,“countryid”,“country”);''和'@ Html.DropDownList(“country”,(SelectList)ViewBag.countrydrop,...)' – 2014-10-27 11:23:03

回答

11

在你的行动改变ViewBag.countrydrop = item8ViewBag.country = item8;并鉴于这样写:

@Html.DropDownList("country", 
        (IEnumerable<SelectListItem>)ViewBag.country, 
        "Select country") 

其实当你写

@ Html.DropDownList( “国家”, (IEnumerable的)ViewBag.country, “选择国家”)

Html.DropDownList(“country”,“Seleclec牛逼国家)

它看起来在IEnumerable<SelectListItem>ViewBag与关键国家,你也可以使用此重载在这种情况下:

@Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown 

Working DEMO Example

0

试试这个

@Html.DropDownList("ddlcountry",(List<SelectListItem>)ViewBag.countrydrop,"Select country") 

在控制器

ViewBag.countrydrop = ds.getcountry().Select(x => new SelectListItem { Text = x.country, Value = x.countryid.ToString() }).ToList(); 
+0

它也从来没有工作 – 2014-10-27 10:47:29

+0

你能够得到你的名单中的国家? – 2014-10-27 10:50:00

+0

断点本身从来没有打电话@ManishSharma – 2014-10-27 10:53:17

1

使用本

var list = new SelectList(countryList, "Id", "Name"); 
ViewBag.countries=list; 
@Html.DropDownList("countries",ViewBag.Roles as SelectList) 
8

如果您正在使用DropDownListFor这样的:

@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList) 

其中MySelectList模型是SelectList类型的属性,这个错误可能会被抛出,如果财产是null

避免这种通过简单的构造函数初始化它,就像这样:

public MyModel() 
{ 
    MySelectList = new SelectList(new List<string>()); // empty list of anything... 
} 

我知道这不是OP的情况,但是这可能帮助像我其中有相同的错误缘于此。

+0

或者类似的东西: MySelectList = new List (); – Sanchitos 2017-08-07 02:51:58

+1

太常见的方式:在POST上发生错误,因此您将视图模型返回到出现错误的页面。但是你并没有刷新POST中丢失的List ,所以它们是空的。而不是一个空引用,从视图中得到一个非常误导性的错误,说某些属性不是特定类型,当你知道它完全没有这个类型时,它应该不是这样的。 – mmcrae 2017-08-29 14:49:34

+0

@mmcrae,我有这个问题一对夫妇时间与POST行动,在那里我忘了再次填充我的下拉项目。 – Alisson 2017-08-29 14:59:47

0

我有一个相同的问题,我找到了解决方案,我应该把代码从编辑方法中的数据库检索下拉列表。它为我工作。

viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>(); 

由于没有做出明确告知我现有的答案,我发布此: Solution for the similar problem

0

在我的情况,因为我还没有初始化的选择列表中的控制器是这样发生的错误。也许它对任何人都有帮助。

相关问题