Why should I use view models?

Where do I put my validation code?

On the view models you should validate everything that’s specific to the application like for example the date should be in en-US format culture, ….

I need to add code to map between business objects and view models.

That’s why there are tools such as AutoMapper.

Different problems arise when you use directly your domain models in the views:

  • The views have specific requirements for displaying the data (localization/globalization) so you either end up with spaghetti code in your views or you put this code on your models so that they become less reusable in other applications because you have polluted them with specific presentation stuff
  • You have different validation requirements based on the view. Let’s take for example the case of Add and Update views. In the Add view the Id property won’t be needed and it won’t be required because you will be inserting a new item. In the Update view the Id property would be required because you would be updating an existing item. It would be difficult to handle those specific validation rules without view models.
  • The models might contain properties such as IsAdmin and then I am leaving to your imagination the implication of a controller action with the following signature:

    [HttpPost]
    public ActionResult CreateUser(BusinessObjectUser user) { ... } 
    

    assuming that you have hidden this property from the underlying form by not including it.

  • The business models don’t change often whereas the UI could change more often. What if your customer asks you to split your screen in two? The way you present the information changes and the way it is formatted also change. If you use your models directly into the views the spaghetiness of your views becomes worse and worse with every change.
  • About 60% of the question I am answering on StackOverflow in the asp.net-mvc tag wouldn’t have been asked if the OP have used a view model.

Leave a Comment