3 Reasons Why Dedicated ViewModels in ASP.NET MVC is a *MUST*
I’d argue that using dedicated view-models in ASP.NET MVC (or any other MVC framework) is one of the things that has changed the way I work for the better. And for the better I mean more maintainable code, better designed code, more robust code — just better in all ways measurable.
Here are three reasons why you should use truly dedicated view-models for any view in ASP.NET MVC.
1. Abstract code beyond your control
If you work on a web team, that is part of a larger team you cannot expect to always have the entire back-end ready at the time you want to start coding a feature for the front-end. But why wait? Even if you don’t have the service layer, the domain models or the database ready, you can just easily create dummy instances of your view-model in a controller and return that to the view.
You can get started coding the UI, the JavaScript, maybe hook up your Backbone models or anything similar.
You are also in complete control of the design of the view-models, and it often turns out that they end up a hell of a lot different from the domain models.
2. Keep view oriented data annotations out of the domain model
You want to use both validation attributes, UIHints, template information and a lot of other view oriented stuff that should stay inside the MVC project.
The problem is that if you throw all these things on the domain model, you suddenly have a dependency on ASP.NET MVC and Razor which means that you must add reference to these dependencies from your lower tiers. Not good!
3. Defend your JavaScript from outside changes
JavaScript is playing a bigger and bigger part in modern web development. So the more JavaScript your write that manipulates your view-models, the more exposed you become to outside changes.
Having a dedicated view-model makes you in control, and not the DBA or any other dude who doesn’t care about the front-end.
How to avoid repeating yourself
It’s probably the worst argument against view-models, that you end up repeating the domain-models. If you think that, you’ve missed something.
The point of a view-model is to make it as closely tied to the view as possible. This will make the view a lot more simple, which is a good thing.
For mapping a domain-model to a view-model and vice-versa, I use AutoMapper which is extremely simple, yet powerful.