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'.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With