Joe
Joe

Reputation: 67

MVC2 ViewData Problems

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?

Upvotes: 3

Views: 4111

Answers (2)

GvS
GvS

Reputation: 52518

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.

Upvotes: 7

Jay Mooney
Jay Mooney

Reputation: 2256

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.

Upvotes: 0

Related Questions