Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the key difference between a ViewModel and a Model in ASP.NET MVC?

What requirements should each of these meet to be classed as either a Model or a ViewModel? (Aside from the directory they live in)

Thanks all,

Dave

like image 363
BanksySan Avatar asked Feb 18 '23 19:02

BanksySan


2 Answers

Although Oded is correct in ViewModel not being part of MVC, many people still use that terminology to describe a model that is essentially one or a combination of translated data classes for presentation purposes.

In a typical implementation, the MVC Web project may not be able to have direct access to the DTO classes, it in turn calls a method in the Core layer which calls the database, retrieves the DTO objects and translates them into a "View Model".

I suppose it helps newcomers (who refer to their data classes as Models) distinguish between the DTO classes and classes built purely for presentation purposes based on the DTO classes.

like image 56
mattytommo Avatar answered Feb 22 '23 02:02

mattytommo


A ViewModel is not part of the MVC pattern, to begin with.

It is part of MVVM.

The MV in both pattern mean Model (as in business/domain model) and View for the UI.

MVC also has a Controller, which is the orchestrator between the view and the model. In terms of the defaults of the Microsoft MVC framework, the Controllers, Views and Models each go into the directory of the matching name.

MVVM has the ViewModel which is a model of the view itself. Since this is not part of the MVC pattern, there is no place for these by default in the MVC templates by Microsoft, though if you wish to introduce this abstraction, you should create a ViewModels directory for them.

like image 29
Oded Avatar answered Feb 22 '23 02:02

Oded