Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should ViewModels be used in every single View using MVC?

I understand you use a ViewModel to store different data from other Models and sources to be used in a View, as a Model will not always hold what you want.

I'm trying to figure out if it is proper to use a ViewModel for every single View. The reason I am asking is for consistency reasons. You could have a View that only needs the Model itself and another View that has to have a ViewModel. Is it good to mix these up between all your Views? Or should every View have a ViewModel?

This is important to know since my Models are directly related to the database, as I'm using Entity Framework 4.1 Code First.

like image 924
TIHan Avatar asked Dec 01 '22 07:12

TIHan


1 Answers

It's not a requirement but it is a best practice.

You want to decouple your database from your presentation as much as possible and having a ViewModel (even if it is identical) gives you that seperation. It also keeps things consistent so you don't have some views with models and some without. This type of design makes you think about all the data you want your views to adhear to and figure out optimizations, see if duplication of data might be occurring, keep data considated to one location, etc.

Think of your ViewModel like a contract with the View.... this View requires X to work.

Little more work up front but it will pay off in the end.

like image 154
Kelsey Avatar answered Dec 06 '22 10:12

Kelsey