问题
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 should I use ViewData and when should I not use it?
Shall input fields like dropdownlists have a seperate view model?
回答1:
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.
回答2:
It's personal choice really. The disadvantage of ViewData is that it's weakly typed and requires casting.
回答3:
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.
回答4:
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.
回答5:
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.
来源:https://stackoverflow.com/questions/3074839/asp-net-mvc-viewdata-and-view-model-best-practices