I have been dealing a day with the dropdowns at mvc 5 with c# and razor.

Example, the one that works. A Hardcoded dropdown means no trouble.

@Html.DropDownList("Example1", 
new List<SelectListItem> 
{ new SelectListItem { Text= "1", Value = "1" }, 
  new SelectListItem { Text = "2", Value = "2" } 
}, 
"Select")

Problem comes when trying to pass the data from the model trough controller to the view. I have found many examples that suppose to work, they do display the dropdown, but fail when trying to save the data. Error is:

There is no ViewData item of type 'IEnumerable' that has the key 'Example'.

From this video the shorter one:

@ controller
public ActionResult Index()
{
   MyDB db = new MyDB();
   ViewBag.Example2 = new SelectList(db.Models, "Id", "Name")
}

@ view
@Html.DropdownList("Example2", "Select");

Again it populates the dropdown but fails to pass the data when saving.

A one little more complex I found here, is top of page when googling the error:

@ controller
List<SelectListItem> selectList = new List<SelectListItem>();
MyDB db = new MyDB();
var query = db.Models;
foreach (var m in query)
{
  selectList.Add(new SelectListItem() { Value = m.Id.ToString(), Text = m.Name }
}
ViewBag.Example3 = selectList;

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

Same result, displays the dropdown, fails to pass the info back.

There is even a fourth one. Which is supposed to be the correct one. I found it here, a very voted answer in stackoverflow. Note it uses a SelectList to jump from controller to view:

@ controller
List<SelectListItem> selectList = new List<SelectListItem>();
MyDB db = new MyDB();
var query = db.Models;
 foreach (var m in query)
  {
      selectList.Add(new SelectListItem() { Value = m.Id.ToString(), Text = m.Name }
    }
 ViewBag.ModelToDropdown = new SelectList(selectList, "Value", "Text");

 @ view
 @Html.DropDownList("Example4", (SelectList) ViewBag.ModelToDropdown, "Select")

Same result:

There is no ViewData item of type 'IEnumerable' that has the key 'Example'.

Any ideas?

It is suppose to be happening because the IEnumerable list is empty, but why they populate the dropdown and the error shows when saving? Again, only the hardcoded example works.

Thanks.

Related posts

Recent Viewed