Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC ViewData and view model best practices

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?

like image 915
Rookian Avatar asked Dec 22 '22 02:12

Rookian


1 Answers

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.

like image 80
amurra Avatar answered Dec 29 '22 08:12

amurra