asp.net-mvc

Is creating ViewModel for Model validation odd and unnecessary?


Is there any good reasons to create ViewModel that copies Model with addition of validation logic? Why not simply extend current model with validation logic? If you will create ViewModel copy, you need to

  1. Create class with corresponding fields (which is not big problem if you have few models to validate, but what if you have many..)
  2. Set automapper, which can be slow, and adds additional logic to your solution (or do it by hand, which is probably, bad idea)
  3. Support Model changes for ViewModel

These problems disappear if you simply extend your basic Model. So why it is so popular to create ViewModel layer?


Solution

  • You can have two views with different validation logic for the same model.

    the classic example is a sign up form, with a single page form vs a multi page wizard.

    In both cases the model is the same, but in the wizard view its legitimate to submit the model half filled in, while the single page version should have all the fields validated.

    Taking this possibility further leads to the one viewmodel per view methodology. Where you always make a viewmodel for a view as a matter of course because you expect to need the flexibility that it offers as a general thing.

    Additionally, its pretty rare that view exactly matches a model. You usually require more than one model plus some odd extra bits. eg user model for the 'logged in as' header, list of models to display plus pagination info.

    You can avoid some of the issues you mention by using ViewModels which simply wrap models and expose their properties where extra logic isn't required