Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: Data Models and View Models

I've read some MVC advice in the past regarding models stating that you should not reuse the same model objects for the domain and the view; but I haven't been able to find anyone willing to discuss why this is bad.

It is my opinion that creating two separate models - one for the domain, one for the view - and then mapping between them creates a lot of duplication, plus tedious mapping code (some of which might be alleviated by things like AutoMapper) that will likely be error prone.

What makes having a separate model for the two concerns worth the trouble of duplication and mapping code?

like image 377
Erik Forbes Avatar asked Jan 24 '09 00:01

Erik Forbes


People also ask

What is model and ViewModel in MVC?

ViewModel = Model that is created to serve the view. ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible. ViewModel serves this purpose. View Model is a model class that can hold only those properties that are required for a view.

What are the three models of MVC?

In fact, in ASP.NET MVC, there are three distinct types of model: the domain model, view model and input model.

What is MVC data model?

The model is the M in MVC. The data model represents the core information that your application is being used to access and manipulate. The model is the center of your application, the viewer and controller serve to connect the user with the data model in a friendly way.

Why do we use ViewModel in MVC?

What ViewModel is. In ASP.NET MVC, ViewModels are used to shape multiple entities from one or more models into a single object. This conversion into single object provides us better optimization.


1 Answers

At its heart, two models is about Separation of Concerns. I want my View to work off of a single Model. I want my Domain Model to represent the conceptual model I build with the domain experts. ViewModel often has technical constraints. Domain Model is about POCO, and not being bound by technical constraints of either data shown (View) or persisted (in a DB or otherwise).

Suppose I have three entities shown on a screen. Does that mean I need to force a relationship between the three? Or just create a ViewModel component object that contains all three items. With a separate ViewModel, View concerns are separated from my domain.

like image 53
Jimmy Bogard Avatar answered Sep 30 '22 08:09

Jimmy Bogard