daz*_*mar 16 c# asp.net-mvc asp.net-mvc-4
在mvc中的绑定下拉列表我总是得到这个错误没有类型'IEnumerable'国家的ViewData项目有关键我不知道如何排序它
视图
@Html.DropDownList("country", (IEnumerable<SelectListItem>)ViewBag.countrydrop,"Select country")
Run Code Online (Sandbox Code Playgroud)
调节器
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();
Run Code Online (Sandbox Code Playgroud)
我不知道我哪里错了,任何人都可以提前帮助我
Ehs*_*jad 18
在您的操作中,更改 ViewBag.countrydrop = item8
为ViewBag.country = item8;
和在View中写入如下:
@Html.DropDownList("country",
(IEnumerable<SelectListItem>)ViewBag.country,
"Select country")
Run Code Online (Sandbox Code Playgroud)
其实当你写的时候
@ Html.DropDownList("country",(IEnumerable)ViewBag.country,"选择国家")
要么
Html.DropDownList("country","Select Country")
它看起来在IEnumerable<SelectListItem>
在ViewBag
与主要国家,你也可以在这种情况下,使用此重载:
@Html.DropDownList("country","Select country") // it will look for ViewBag.country and populates dropdown
Run Code Online (Sandbox Code Playgroud)
请参阅工作演示示例
Ali*_*son 12
如果你这样使用DropDownListFor
:
@Html.DropDownListFor(m => m.SelectedItemId, Model.MySelectList)
Run Code Online (Sandbox Code Playgroud)
其中,MySelectList
在该模型类型的属性SelectList
,如果属性是这样的错误可能会被抛出null
.
通过在构造函数中简单地初始化它来避免这种情况,如下所示:
public MyModel()
{
MySelectList = new SelectList(new List<string>()); // empty list of anything...
}
Run Code Online (Sandbox Code Playgroud)
我知道这不是OP的情况,但这可能会帮助像我这样因此而出现同样错误的人.