views:

181

answers:

5

The initial situation is that I map my domain model into a presentation model.

I have to display an update/create formular with textboxes and a dropdownlist.

Should the viewmodel contain a list for the dropdownlist or should I pass the data for the dropdownlist by using ViewData?

When schould I use ViewData and when don't I should use it?

Shall input fields like dropdownlists have a seperate viewmodel?

Are there some other opinions about this topic?

+1  A: 

It's personal choice really. The disadvantage of ViewData is that it's weakly typed and requires casting.

fearofawhackplanet
+1  A: 

You should pass the list as part of your Model. Or, if the list is pretty pervasive (like, say, a list of States or a Yes/No list), you can create a static list in a static class that can be referenced directly in your ViewPage. I don't see why you'd want to pass it via ViewData, as you'd have to cast your list in your ViewPage.

ewwwyn
http://weblogs.asp.net/rashid/archive/2009/11/27/extending-asp-net-mvc-2-templates.aspx
Rookian
+1  A: 

You might want to take a look at NerdDinner, in particular the DinnerFormViewModel and the list of countries to choose from. Basically, they have a Dinner model (used for the index view, where they need a collection) plus a DinnerFormViewModel which contains a single Dinner instance and a SelectList for the countries. The create view (aptly named DinnerForm) is, of course, strongly typed and takes a DinnerFormViewModel.

+2  A: 

I found something very interesting here ... http://weblogs.asp.net/rashid/archive/2009/11/27/extending-asp-net-mvc-2-templates.aspx

Exactly what I need.

Rookian
I take this one step farther. Instead of setting a ViewData field in the controller, I have an ActionFilter that looks for null option lists on my model and populates them automatically based on the generic type. (Granted this won't work if you have some view-specific logic for what options to show.) For example `Options<UserType>` would get populated with a list off all UserTypes.
Ryan
+1  A: 

I tend to try and use ViewData as little as possible since you always need to cast values, you need to do error checking for nulls or for keys that don't exist and it clutters the views in my opinion.

I tend to try and use viewmodels whenever possible since I find strongly typing the view to the model as a cleaner approach.

I would put as much of the data into the viewmodel as possible, but only what makes sense. For data that shouldn't belong in the viewmodel I would pass in as ViewData, but would try to keep the amount to a minimum.

As far as you question goes for input fields, if they are all related I would make a ViewModel for that instead of passing in 5 or 10 pieces of data in the ViewData since logically grouping them in one place would make sense. It really is a matter of preference, but I found this approach to be the best for me.

amurra