没有名为“country”的“IEnumerable<SelectListItem>”类型的ViewData项。

23

在MVC中绑定下拉框时,我总是会遇到这个错误:没有名为“country”的类型为'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();

我不知道如何解决它。


7
如果你遇到了这个错误,那么它意味着ViewBag.countrydrop的值是null。可能是代码未被执行来填充它,或者只有在你提交表单后并返回视图时才出现这种情况(而且你没有再次填充ViewBag.countrydrop)。 - user3559349
1
考虑简化您的代码为 ViewBag.countrydrop = new SelectList(coun, "countryid", "country");@Html.DropDownList("country",(SelectList)ViewBag.countrydrop, ...) - user3559349
1
如果您打开接受的答案中的演示,并将 ViewBag.country = item8; 更改为 ViewBag.countrydrop = item8;,并将 @Html.DropDownList("country","Select country") 更改为 @Html.DropDownList("country",(IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country"),即根据您发布的代码,您会发现它也可以工作。问题不在于命名,而在于 ViewBag 属性为 null,您现在可以通过将 ViewBag.countrydrop = item8; 更改为 ViewBag.countrydrop = null; 进行测试。 - user3559349
@StephenMuecke 哎,伙计,你说得对,它是null,那么如何填充它呢? - dazzling kumar
2
错误是在初始加载时发生的,还是在您提交并返回视图时发生的? - user3559349
显示剩余3条评论
12个回答

26

如果你正在像这样使用 DropDownListFor

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

如果模型中的属性MySelectListSelectList类型的属性,当该属性为null时可能会引发此错误。

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

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

这种情况经常发生在POST操作中。确保在重新渲染视图之前分配了某些内容。


3
常见情况:在POST时发生错误,因此您会将视图模型带有错误返回到页面。但是您没有刷新丢失在POST中的List<SelectListItem> - 因此它们为null。而不是空引用,您会从视图中得到一个非常误导性的错误,说某个属性不是特定类型,而您完全知道它不应该是这种类型等。 - Don Cheadle
@mmcrae 没错,我在使用POST操作时也遇到过这个问题,因为我忘记重新填充下拉列表了。 - Alisson Reinaldo Silva
“property was null”这个注释是关键,表明ViewBag项目由于某种原因未被填充。 - Mark Schultheiss
1
这个修复可能对大多数问题无效,因为此代码会使列表为空,这意味着在 postback 后,您的下拉列表变为空,因此您无法插入第二条记录。我不小心点了赞,现在我无法撤销我的投票。 - Ashok kumar
1
@SteveSmith 哈哈,为什么要简单化呢,复杂化才是王道,对吧? :) - Alisson Reinaldo Silva
显示剩余3条评论

24

在您的操作中将 ViewBag.countrydrop = item8; 更改为 ViewBag.country = item8; ,并在视图中按如下编写:

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

实际上,当你写下以下代码时:

@Html.DropDownList("country", (IEnumerable)ViewBag.country, "选择国家")

或者

Html.DropDownList("country", "选择国家")

它会在ViewBag中寻找键为countryIEnumerable<SelectListItem>,在这种情况下也可以使用此重载:

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

查看工作演示示例


不错的Sajjad,也许是第一次看到一个用于MVC的dotnet fiddle!! - Irf
@Irf 每个人都有第一次!! - Ehsan Sajjad

4
请注意,选择列表作为 null 提交,因此您的错误会抱怨找不到 viewdata 属性。
在 POST 操作中始终重新初始化您的选择列表。
更多解释请参考: Persist SelectList in model on Post

1
尝试这个。
@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();

你能在列表中获取国家吗? - Manish Sharma
@dazzling kumar,请更改您的下拉列表名称。我已经更新了我的代码,请检查并在视图“country”中将您的DropDownList名称更改为“ddlcountry”,然后它就可以工作了。 - Manish Sharma

1
尝试这个。 控制器:
List<CountryModel> countryList = db.countryTable.ToList();
ViewBag.Country = new SelectList(countryList, "Country", "CountryName");

0

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

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

}


<div class="form-group">                    
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
  <div class="col-md-10">
 @Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { @class = "w3-select ", @required = "true" })
</div>
</div>

0

可能是针对ASP.NET MVC框架的

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

或者ASP.NET Core MVC

<select class="class" id="country"
asp-items="@(new SelectLits(ViewBag.countrydrop,"Value","Text"))">

0

你可以使用这个:

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

0

我曾经遇到过同样的问题,后来我找到了解决方案,即将从数据库检索下拉列表的代码放在编辑方法中。这对我起作用了。 类似问题的解决方案


0
在我的情况下,错误发生是因为我没有像这样在控制器中初始化选择列表:
viewModel.MySelectList = new List<System.Web.Mvc.SelectListItem>();

由于现有的回答没有让我清楚明白,因此我发布了这篇文章。希望它能帮助到任何人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接