Tired of looking for errors in log files? Use OneTrueError - Automatic exception management for .NET.

Three reasons to why you should use view models

I’m answered a couple of questions at stackoverflow regarding the benefit of view models. Here is a summary of all my answers focusing on view models in ASP.NET MVC.

Reason 1: Remove logic from your views.

When you start working with ASP.NET MVC you’ll most likely ask yourself why you should use a view model. Using your domain model or entity model works perfectly fine. And it does. For a while. But as you continue to use your models you’ll discover that you have to add some adaptations in your views. Here is a typical usage adaptation (using razor view engine):

Hello @model.UserName

Your age: @(model.Age != 0 ? model.Age.ToString() : "n/a")

Not so bad, is it? The problem is that you have introduced logic into your view, which is bad for two reasons:

A) You can not unit test that code, and the only way to make sure that it works is user testing.
B) You need to repeat that code for every view that intends to use your model (code duplication = code smell)

All those small adaptations will lead to a big mess eventually.

Reason two: Security

One of the biggest advantages with view models are to remove security risks. Your database objects or domain objects will most likely contain properties that the user should not be able to change. It can be a property called IsAdmin or Reputation.

All those properties will automatically be changed by the model binder if they exist in the model (and are posted in the FORM which is quite easy to do if you know HTML). Simply remove them from the view model and they’ll never be changed.

Reason three: Loose coupling

By using domain models or entity models you are adding coupling between your lower layers and the presentation layer and that is seldom good. Google “loose coupling” to find out more.

Basically it means that if you change your domain/entity model you have to change all your views that use that model. If you use a ViewModel you only have to change the code that maps between an entity/domain model and the view model.

How to make the model mapping easier

I usually use a framework called AutoMapper to manage the mappings between viewmodels and other models. AutoMapper and it’s alternatives usually let yuo use a single line of code to do the mapping.

This entry was posted in Architecture, CodeProject and tagged . Bookmark the permalink.
  • http://twitter.com/moesmp Mohsen Esmailpour

    could you please explain how to remove logic from view with ViewModel in such scenario like @(model.Age != 0 ? model.Age.ToString() : “n/a”).