Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices with ASP.NET MVC view models

I ask myself how do I create a view model correctly.

For instance, I have an edit view with some text boxes and a dropdownlist.

Should I separate the dropdown list into a new view model or shoud the edit view have one viewmodel with a list for the dropdownlist?

Or generally speaking, should I separate special input fields in separate view models?

When should a view have more than one view model and when not?

like image 522
Rookian Avatar asked Sep 06 '10 20:09

Rookian


2 Answers

There's no clear rule of how to create and organize your view models correctly. Your question is too vague to be answered because you provided too little context.

I usually group view models according to functional blocks/parts of the screen they represent. So for example imagine that you have a complex form composed of multiple sections/fieldsets like contact details, delivery address, billing information, etc... An address could be composed of street, zip, city and country dropdown. I would create an address view model containing those four properties so that it can be reused in multiple views/partial views. This will also make validation easier as dependent properties will be packed into the same view model like validate for example that the given zip corresponds to the city and that the city belongs to the selected country.

For instance, I have an edit view with some text boxes and a dropdownlist.

Should I separate the dropdown list into a new view model or shoud the edit view have one viewmodel with a list for the dropdownlist?

I would say no, if those fields are somehow functionally related.

Conclusion: you will have to find the right balance between having a view model per field on the screen and having a single view model per application.

like image 101
Darin Dimitrov Avatar answered Nov 19 '22 13:11

Darin Dimitrov


I prefer the approach of one view model per view/partial view. This is in my opinion the best approach if you believe the view model's single purpose should be modeling the view. This paradigm also supports the use of strongly typed views thus providing compile time error checking for your views model binding and you get the added benefit of intellisense. In the scenarios where you want to re-use some logic, I find it can often be satisfied by re-factoring the view into partial views and providing these partials with their own view models. It should be emphasized that no domain logic should exists in your view models as it really belongs in a domain model.

like image 42
Blegger Avatar answered Nov 19 '22 11:11

Blegger