views:

1437

answers:

2

I'm trying to pass a list of a few items to a view via the ViewData to create a drop down list. This shouldn't be too difficult, but I'm new to MVC, so I'm probably missing something obvious.

The controller assigns the list to the ViewData:

ViewData["ImageLocatons"] = new SelectList(gvr.ImageLocations);

and the view tries to render it into a drop down list:

<%= Html.DropDownList("Location", ViewData["ImageLocations"] as SelectList) %>

However, when I run it, I get this error: There is no ViewData item of type 'IEnumerable' that has the key 'Location'.

Any ideas why this isn't working? Also, shouldn't it be looking for the key "ImageLocations" rather than location?

+7  A: 

If you use:

ViewData["Location"] = new SelectList(gvr.ImageLocations); 

and

<%= Html.DropDownList("Location") %> 

Your life will be a lot easier.

Also check out the typo (missing i) when setting the ViewData in your example (ImageLocatons => ImageLocations). This causes the second parameter you pass to DropDownList to be null. This will cause the MVC engine to search for Location.

GvS
Wow. I had a spelling error. I'm using the other method you suggested now. Thanks a lot!
Joe
Nice catch. +1 for seeing the typo. I had to re-read a few times even after you pointed it out :-)
Chris Melinn
A: 

Is it possible that your ViewData was reset?

Try putting a break point in your View on the line where you emit the drop down list.
Then do a quick watch on ViewData["ImageLocations"].

Make sure that there is a value here when the view tries to use it.

Jay Mooney