Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

There are a couple of posts about this on Stack Overflow but none with an answer that seem to fix the problem in my current situation.

I have a page with a table in it, each row has a number of text fields and a dropdown. All the dropdowns need to use the same SelectList data so I have set it up as follows:

Controller

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name"); 

View

<%= Html.DropDownList("submarket_0", (SelectList)ViewData["Submarkets"], "(none)") %> 

I have used exactly this setup in many places, but for some reason in this particular view I get the error:

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

like image 218
Jimbo Avatar asked May 17 '10 13:05

Jimbo


2 Answers

Ok, so the answer was derived from some other posts about this problem and it is:

If your ViewData contains a SelectList with the same name as your DropDownList i.e. "submarket_0", the Html helper will automatically populate your DropDownList with that data if you don't specify the 2nd parameter which in this case is the source SelectList.

What happened with my error was:

Because the table containing the drop down lists was in a partial view and the ViewData had been changed and no longer contained the SelectList I had referenced, the HtmlHelper (instead of throwing an error) tried to find the SelectList called "submarket_0" in the ViewData (GRRRR!!!) which it STILL couldnt find, and then threw an error on that :)

Please correct me if im wrong

like image 166
Jimbo Avatar answered Oct 03 '22 04:10

Jimbo


Old question, but here's another explanation of the problem. You'll get this error even if you have strongly typed views and aren't using ViewData to create your dropdown list. The reason for the error can becomes clear when you look at the MVC source:

// If we got a null selectList, try to use ViewData to get the list of items. if (selectList == null) {     selectList = htmlHelper.GetSelectData(name);     usedViewData = true; } 

So if you have something like:

@Html.DropDownList("MyList", Model.DropDownData, "")

And Model.DropDownData is null, MVC looks through your ViewData for something named MyList and throws an error if there's no object in ViewData with that name.

like image 35
hawkke Avatar answered Oct 03 '22 06:10

hawkke