Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should data annotations be on the Model or the View Model?

I've been used to decorating data model classes with data annotation attributes, but the purist in me baulks slightly at including purely presentational attributes such as display format here. I am, however, quite happy to keep validation centric attributes here. One good reason I have to continue keeping all annotations etc. in the data model is that my view model aggregates data model classes, e.g. my ViewModelBase.DetailItem<TEntity> property in the view model is just a reference to an entity class in my data model. If I wanted to move presentational annotations to the view model, I would have to quite radically revise my design to one where I duplicate data model properties in my view model and use an object mapping tool to populate view model objects based on data model objects.

Where should I be doing my data annotations?

Just BTW, this is what my rough draft ViewModelBase looks like:

public class ViewModelBase<T>
{
    public virtual string PageTitle { get; set; }
    public virtual string ViewHeading { get; set; }

    public virtual ViewMode ViewMode { get; set; }
    public virtual IEnumerable<T> ItemList { get; set; }
    public virtual T DetailItem { get; set; }
}
like image 701
ProfK Avatar asked Dec 15 '10 16:12

ProfK


1 Answers

Validation should at least be performed at the view model because this is what you receive from the view. Also the validation is always performed in the context of a given view. So you could have two different view models corresponding to two different views but mapped to a single model class and because the validation could be different depending on the view, this validation should be performed on the view model. If you performed the validation on the model then you would have hard time to distinguish between the two cases, because you could have a situation where a property is required in the first view, but not required on the second view. So if you are using data annotations to perform validation then you should decorate your view model with them.

like image 94
Darin Dimitrov Avatar answered Oct 12 '22 19:10

Darin Dimitrov