Why do we use ViewModels?

I have recently started working as a web developer. I work with ASP .NET MVC 4 and NHibernate.

At my work-place, we are strictly made to use viewmodels to transfer data to and fro between a controller and a view. And the viewmodels are not supposed to contain any object of a model. I understand that it is a sort of a tier between the controller and the view.

But I find it repetitive and redundant to write a viewmodel class even if we can directly send the model's object to the view (in most cases).

For example, if i want to display an order i can do this in the controller's action -

return View(Repository.Get<Order>(id));

But instead, I have to write a viewmodel, fill it with the fetched order and then pass it to the view.

So, my question is, what purpose does writing viewmodels serve when we can use the model's object as it is?


Solution 1:

For smaller projects, you're right. I hear your argument and sympathise - however there are good reasons for this, drudged and repetitive work, especially in larger and more complicated applications:

  • It's essential to perform all processing within the Controller's action. However in the example you've given, the Repository.Get method might return a lazily-evaluated IQueryable object, which would mean the DB wouldn't be hit until the View is evaluated. For a variety of reasons this is bad. (A workaround is to call .ToList while still in the controller).
  • "A view should not contain any non-presentational logic" and "You should not trust the View" (because a View could be user-provided). By providing a Model object (potentially still connected to an active DatabaseContext) a view can make malicious changes to your database.
  • A View's data-to-display does not always map 1:1 with its Model's data, for example consider a User Details page:

    A User's EF Model object represents its entity in the database, so it probably looks like this: User { UserId, UserName, PasswordHash, PasswordSalt, EmailAddress, CreatedDate }, whereas the fields on a "User details" page are going to be User { UserId, UserName, Password, ConfirmYourPassword, EmailAddress }, do you see the difference? Ergo, you cannot use the EF User model as the view model, you have to use a separate class.

  • The dangers of model manipulation: if you let ASP.NET MVC (or any other framework) do the model binding to the incoming HTTP POST Request then (taking the User details example above), a user could reset anyone's password by faking the UserId property value. ASP.NET will rewrite that value during binding and unless you specifically sanitize it (which will be just as drudgeful as making individual ViewModels anyway) then this vulnerability will remain.

  • In projects with multiple developers working in a team situation, is is important that everything is consistent. It is not consistent to have some pages using bespoke ViewModels but other pages using EF Models because the team does not share a concious mind, things have to be documented and generally make-sense. For the same reason a single developer can get away without putting excessive XML documentation in his source code, but in a team situation you'll fall apart if you don't.

There is a slight workaround in your case I'll share with you, but please note the preconditions:

  • Your views can be fully trusted
  • Your views contain only presentational logic
  • Your application is largely CRUD
  • Your views correspond 1:1 with each EF entity model (i.e. no JOINs)
  • Your views only deal with single Simple models for POST forms, not Complex models (i.e. an object graph)

...then you can do this:

  • Put all one-way, non-form-related data into your ViewData collection, or the ViewBag in MVC 4 (or even a generic ViewData<T> if you're hardcore). This is useful for storing HTML page titles and sharing data with Master pages.
  • Use your fully-evaluated and loaded EF models as your View<TModel> models.

But use this approach with caution because it can introduce inconsistency.

Solution 2:

Well, i'm starting to think the pragmatic approach to every problem is required and not to just subscribe to the purist architectural standards out there. Your app may be required to run in the wild and be maintained by many developers serving a large set of client etc. and this may direct or drive your architecture.

  • The ViewModel is essential when you want a separation of concerns between your DomainModel (DataModel) and the rest of your code.

The less dependencies you have between the Model, View and Controller the easier down the line it will be to make changes to the DomainModel without breaking the interface contracts in the View and Controller etc. etc. But once again it's something to be pragmatic. I like the approach as code re-factoring is a big part of system maintenance - refactoring may include a simple spelling mistake on a property of a Model - that change could ripple through the code to the Contract level if the dependencies are not separated; for example.

  • The ViewModel is used to translate the data between your DomainModel and you Views

A simple example of a datetime stored in Informix has to be translated to a .Net DateTime. The ViewModel is the perfect place to do this translation and does not force you to put translation code in all sorts of unwanted places.

One attribute of a good design [of anything] is the ability to replace or modify a part of the implementation with little or no affects to the rest of the parts of the system. But this takes effort and time to achieve - it's up to you to find that practical balance between a perfect design and a design that is just enough

But yeah, there are many other good reasons to use certain patterns - but the bottom line is this:

Nothing forces you to use ViewModels... ASP.NET MVC won't force you. Take advice from the pragmatist inside you.

Solution 3:

If you use same Models as your ViewModels, your application should be very small and simple and should contain only CRUD operations. But if you are building large or enterprise applications with large teams (with two or probably more developers), you should have concepts like Dependency Injection, Services, Repositories, Façades, Units of Work, Data Access Objects etc.

To simplify your mapping needs between Models and ViewModels, you can use AutoMapper https://github.com/AutoMapper/AutoMapper

or install with nuget Install-Package AutoMapper

Solution 4:

According to me, it is essential to have one more layer(ViewModel) on top of Model layer for complex applications that performs most of the CRUD operations because it has following advantages:

  1. To establish loose coupling between Model and Controller. So that any DataModel related modifications will not be affected to Controller.
  2. If you've implemented your application's ViewModel layer correctly by providing maximum level of IOC(Inversion of Control) via DI(dependency Injection using Unity/other frameworks), etc., it will also help you to MOQ your ViewModels(dependencies) for testing only the controller's logic.