Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which layer should construct a View Model?

I'm using the S#arp Architecture. I can't remember where I read it, but I understand that view models should be stored at the service layer, and your views should submit the view model to the service for processing.

My question then is this: Which layer should construct the view model? Should it be at the service layer, with the controller requesting it? Or should the controller construct the view model itself? There is also a question about updating the view model since, if it contains collections, and the model state is invalid, you will also need to repopuplate any lists.

Any suggestions?

like image 386
Matt Brailsford Avatar asked Apr 27 '10 09:04

Matt Brailsford


People also ask

What are view models used for?

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.

What should ViewModel contain?

The viewmodel may expose the model directly, or properties related to the model, for data-binding. The viewmodel can contain interfaces to services, configuration data, etc in order to fetch and manipulate the properties it exposes to the view.

What is view model in database?

A view model represents the data that you want to display on your view/page, whether it be used for static text or for input values (like textboxes and dropdown lists) that can be added to the database (or edited). It is something different than your domain model . It is a model for the view.

What is ViewModel in ASP NET MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

What is the difference between View and View Model?

VIEW: ( Platform Specific Code – USER INTERFACE ) What the user sees, The Formatted data. VIEWMODEL: ( Reusable Code – LOGIC ) Link between Model and View OR It Retrieves data from Model and exposes it to the View. This is the model specifically designed for the View.


2 Answers

As per the traditional approach or theory wise, ViewModel should be part of User Interface(UI) layer. At least the name says so.

But when you get down to implementing it yourself with Entity Framework, MVC, Repository etc, then you realise something else.

Someone has to map Entity Models with ViewModels(DTO mentioned in the end). Should this be done in A) the UI layer (by the Controller), or in B) the Service layer?

I go with Option B. Option A is a no-no because of the simple fact that several entity models combine together to form a ViewModel. We may not pass unnecessary data to UI layer, whereas in option B, the service can play with data and pass only the required/minimum to the UI layer after mapping (to the ViewModel).

But, let us assume we go with Option A, we put ViewModel in the UI layer(and entity model in Service layer).

If the Service layer needs to map to the ViewModel, then the Service layer need to access ViewModel in UI layer. Which library/project? The Viewmodel should be in a separate project in the UI layer, and this project needs to be referenced by Service Layer. If the ViewModel is not in a separate project(.dll), then there is circular reference, so no go. It looks awkward to have Service layer accessing UI layer but still we could cope with it.

But what if there is another UI app using this service? What if there is a mobile app? How different can the ViewModel be? Should the Service access the same view model project? or will all UI projects compete?

After these considerations my answer would be to put the Viewmodel project in Service Layer. Every UI layer has to access the Service layer anyways! And there could be a lot of similar ViewModels that they all could use (hence mapping becomes easier for service layer). Mappings are done through linq these days, which is another plus.

Lastly there is this discussion about DTO. And also about data annotation in ViewModels. ViewModels with data annotations cannot reside in service layer. So then DTO will be an exact copy of ViewModel with a one on one mapping between the two(say with AutoMapper). Again DTO still has the logic needed for the UI(or multiple applications) and resides in Service Layer. And the UI layer ViewModel is just to copy the data from DTO, with some 'behaviour'(eg: attribute) added to it.

[Now this discussion is about to take an interesting turn read on...:I]

And don't think data-annotation attributes are just for UI. If you limit the validation using System.ComponentModel.DataAnnotations.dll then the same ViewModel can also be used for front-end & backend validation(thus removing UI-residing-ViewModel-copy-of-DTO). Moreover attributes can also be used in entity models. Eg: using .tt, Entity Framework data models can be autogenerated with validation attributes to do some DB validations like max-length before sending to the back end. Another advantage is that if backend validation changes in DB then .tt (reads DB specifics and create the attribute for entity class) will automatically pick that up. This can force UI validation unit tests to fail as well, which is a big plus(so we can correct it and inform all UIs/consumers instead of accidentally forgetting and failing). Yes, the discussion is moving towards a good framework design. As you can see it is all related: tier-wise validation, unit test strategy, caching strategy, etc.

Although not directly related to the question. 'ViewModel Façade' (viewmodel inside another viewmodel) & 'command' mentioned in this must watch channel 9 link is also worth exploring(@11:48 it starts)

like image 154
Blue Clouds Avatar answered Oct 29 '22 21:10

Blue Clouds


I create view models inside controllers. Controllers take domain entities (retrieved from database by model binders), possibly inside other view models, contact repositories for additional data, create new view model, and pass it to appropriate view (or redirect). So controllers responsibility is to prepare view/viewmodel according to input domain data (and handle errors of course).

You can look here for alternative to creating view models in controller. This technique moves view model creation outside actions, so that not only controller actions accept pure domain objects, but they also return pure domain objects. I wouldn't say it's appropriate in all cases, but it's very interesting to learn.

The above technique, related to AutoMapper, also raised questions similar to "should I pass viewmodels to service layer". No you don't. If you need to pass complex object to service or domain layer, you define this object in the appropriate service/domain layer and use it to pass data to those layers. This object then can be easily mapped to/from view models (for example, using AutoMapper). But your lower layers (service/domain) should not be coupled to upper layers (view/controllers). Not in this case, not in others. Never low level layers should depend on something defined above them.

like image 30
queen3 Avatar answered Oct 29 '22 22:10

queen3