问题
i start to study mvc, try to add dropdownlist, make construction
<%= Html.DropDownList("ddl") %>
but it show error
There is no ViewData item of type 'IEnumerable' that has the key 'ddl'
why? i use simple code, only pass name parameter, so why the error?
回答1:
"There is no ViewData item of type 'IEnumerable'"
It means that helper method is expecting an item of type 'IEnumerable'
for e.g, List<>
with an Id 'ddl'
If you are trying to display a DropDownList which has items from some static source, here is one way to do this.
// create new IEnummerable
List<string> ddl =
new List<string>(new [] {"item1","item2" };
// add Items
ddl.Add("Item1");
ddl.Add("Item2");
// return View which holds ddl now
ViewData["ddl "] = ddl ;
return View();
For more insight have a look at
- Understanding HTML Helpers
- How to create a DropDownList with ASP.NET MVC
回答2:
Actually Html.DropDownList
is an HTML helper that create html select
element. When you pass ddl
as argument it expects to get an array or list or something like that (an object implementing IEnumerable
interface) to populate the dropdownlist. try it like this:
In Controller:
ViewData["ddl"]=new string[]{'Jan', 'Feb','Mar','Apr'.......'Dec'};
then it will create a select element containing the given values. For more information read this article.
回答3:
Here is an example of adding a DropDownList in ASP.NET-MVC. You need to provide an item of type 'IEnumerable' with a key 'dll' in the ViewData, as the error says.
来源:https://stackoverflow.com/questions/2308731/asp-net-mvc-dropdownlist-no-viewdata-item