Should ViewModels be used in every view using MVC?

I understand that you are using ViewModel to store different data from other models and sources that will be used in the view, since the model will not always contain what you want.

I am trying to figure out if the ViewModel is correct for each individual view. The reason I ask is the reasons for consistency. You may have a view that needs only the model itself and another view that the ViewModel should have. Is it good to mix them between all your ideas? Or does each view have a ViewModel?

This is important to know, since my models are directly connected to the database, since I use Entity Framework 4.1 Code First.

+4
source share
2 answers

This is not a requirement, but it is best practice.

You want to share your database from your presentation as much as possible and have a ViewModel (even if it is identical) gives you this separation. It also maintains consistency, so you do not have some views with models, and some without them. This type of design makes you think about all the data that you want your views to be able to make adhear and find out their optimization, see if data can be duplicated, store data in one place, etc.

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

A little more work, but in the end it will pay off.

+13
source

Personally, I like to ignore what is sent to my views from my models.

The reason is that the requirements are changing, and with the view model I can quickly include the parts of the data I need without polluting my models.

This comes into play even more when your models are framed. Distraction of the details of the model may be valid in the future in case of changes in models associated with the frame.

It is also worth remembering that your views are independent of your controllers and models. You may find that using the view model, you can more easily use your view using the controller methods than when the view is tied to the model itself.

+7
source

All Articles