Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who populates the ViewModel in ASP MVC 5

Whose responsibility is it to populate the values in an ASP MVC 5 architecture (C#, EF), for e.g. if we have PurchaseRecordsViewModel , PurchaseRecords Domain Model , PurchaseController

  • Does the code to populate data (time, cost etc) go it the viewmodel, right in its very own the viewmodel go in the PurchaseRecordsViewModel ?

  • Or, does the code go in the Action method of the PurchaseController

like image 249
aggie Avatar asked Oct 15 '14 20:10

aggie


People also ask

What is ViewModel in ASP.NET 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.

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.

Is a ViewModel the same as a controller?

While the ViewModel is an optional pattern the Controller is a must, if you are going the MVC way. The ViewModel encapsulates presentation logic and state, The Controller orchestrates all the Application Flow.


1 Answers

View models are typically just dumb collections of properties. Populating a view model typically rests inside of your service layer or, if you don't have one, your action method.

Think of the roles this way.

  • A domain model is a direct mapping to a database table.
  • A view model is a collection of properties needed to display a view.
  • A service layer gets/uses one or more domain models and populates a view model.
  • A service layer also can take a view model and create/update one or more domain models
  • A controller action method is the glue between the two. It calls a service layer to get (GET) a view model and passes it to a view. These action methods also take (POST) a view model and pass it to the service layer to do whatever needs to be done to it.

Another question typically asked is why can't I use domain models for a view? You can, but typically you run into things like, needing data from more than one domain model, not needing all the properties that are in the domain model and lastly, you now would have to worry about properties being updated on the domain model that you did not intend.

like image 52
Tommy Avatar answered Nov 07 '22 07:11

Tommy