Correct way to validate model in ASP.NET MVC 2 and ViewModel apporach

I am writing an ASP.NET MVC 2 application using NHibernate pattern and repository. I have an assembly that contains my model (business entities), moreover, in my web project I want to use flattened objects (possibly with additional properties / logic) as ViewModels. These virtual machines contain UI-specific metadata (for example, the DisplayAttribute used by the Html.LabelFor () method).

The problem is that I don't know how to implement the validation so that I don't repeat myself at different levels (in particular, validation rules are written once in the Model and propagated to the ViewModel).

I am using DataAnnotations in my ViewModel, but that means the rules do not apply to the model itself. One approach I am considering is inferring ViewModels from business objects adding new properties / overriding old ones, thus keeping validation metadata between them, however this is an ugly workaround.

I have seen the Automapper project that helps match properties, but I'm not sure if it handles ASP.NET MVC 2 metadata correctly. Is it difficult to use a custom validation system in asp.net mvc 2?

Do you have templates to help you keep DRY on validation?

+2


a source to share


1 answer


It's good to repeat the check. The trick is to place where it fits.

In your case - in the user interface, checking the UI logic (the view model props should not be null, in the correct format, etc.), in the business layer - checking the business logic (the account has money, etc.) .).

Don't use DRY as an excuse to violate SRP !: P



The presented models should separate your business layer from the presentation role.
Don't glue everything together.


I think Automapper cannot handle this. :)

+2


a source







All Articles