Search code examples
asp.net-mvcdrop-down-menuviewdata

asp.net mvc dropdownlist no ViewData item


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?


Solution

  • "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