This project is read-only.

Reusing validation attributes in custom ViewModels

Jan 13, 2010 at 7:55 PM


When I started using xVal I was mostly implementing action methods which used domain model objects as a viewmodel. This approach works fine most of the time, but there are cases when I need a viewmodel which contains only a subset of the model's properties.

The only workaround I have found for that scenario is creating a custom viewmodel containing those properties and adding validation attributes to the viewmodel itself.

This approach works, but it's far from perfect since I have to repeat the same validation attributes that are already present on the domain model object.

The buddy class technique doesn't help here since xVal throws when the metadata class has properties that are not present on the viewmodel.

Is there any elegant workaround to this?



Jan 14, 2010 at 2:33 AM

Why not just create your own class that derives from DataAnnotationsRuleProvider (overriding the GetRulesFromTypeCore method) or just implement IRulesProvider yourself?  If you have some mapping between your view model and domain model objects, you can just find the map to your domain model and then return the rules for that type, not for the view model type.