没有类型为’IEnumerable ‘的ViewData项具有关键国家/地区

在mvc中的绑定下拉列表我总是得到这个错误没有类型’IEnumerable’国家的ViewData项目有关键我不知道如何排序

视图

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

调节器

 List coun = new List(); coun = ds.getcountry(); List item8 = new List(); 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; 并在视图中写这样:

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

其实当你写的时候

@ Html.DropDownList(“country”,(IEnumerable)ViewBag.country,“Select country”)

要么

Html.DropDownList(“country”,“Select Country”)

它在具有键国家的 ViewBag中查找IEnumerable ,在这种情况下您也可以使用此重载:

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

请参阅工作演示示例

如果你像这样使用DropDownListFor

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

其中模型中的MySelectListSelectList类型的属性,如果属性为null则可能抛出此错误。

通过在构造函数中简单地初始化它来避免这种情况,如下所示:

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

我知道这不是OP的情况,但是这可能会帮助像我这样因此而出现同样错误的人。

请注意,选择列表将发布为null,因此您的错误会导致无法找到viewdata属性。

始终在POST操作中重新初始化您的选择列表。

有关进一步说明: 在Post上的模型中保留SelectList

用这个

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

试试这个

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

在控制器中

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

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

在我的情况下,发生错误是因为我没有初始化控制器中的选择列表,如下所示:

 viewModel.MySelectList = new List(); 

由于现有的答案都没有向我说明,我发布了这个。 也许它可以帮助任何人。

你的代码是正确的,因为在某些情况下它不起作用,我也不知道错误来自哪里,但这可以帮助你解决问题,将代码移动到视图的头部,如下所示:

 index.cshtml: @using expert.Models; @{ ViewBag.Title = "Create"; Layout = "~/Views/Shared/_Layout.cshtml"; Manager db = new Manager(); ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE"); } 
@Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { @class = "w3-select ", @required = "true" })