1

The DataAnnotations validation happens in the default model binder and most of the examples I've seen uses the Model.IsValid in the Controller to verify if a model is valid or not. Since my controller action calls a business layer method and I like to validate the entity there:

  1. Do I have to explicitly switch off the model binder validation?
  2. How do I validate the entity in the business layer. In other words, how do I trigger validation given an object?
  3. Also, I am using View Models. Do I add the validation attributes to the view model? If so, since View models are being tied to the UI, what about validation at the business layer??

1 Answer 1

3

I'm gonna start by answering your question #3: yes, when using view models, add Data Annotation validation attributes right on the properties on your view model. As you pointed out, the view models are tied to the UI so they have presentation concerns and the validation is strictly for UI input validation. The validation attributes you apply here will be automatically invoked by the framework and you can check ModelState.IsValid in your controller (which you also pointed out).

In reference to validating objects in your business layer, there are numerous ways to do this. For example you could also use data annotations on your business layer domain model entities as well. You could also use other frameworks like Enterprise Library validation application block, Fluent Validation, etc. But in this case, you're probably going to be making an explicit call to validate your domain objects (and each of these frameworks has their own mechanism for doing so). I'm presuming your mapping between your view models and domain models (probably with something like AutoMapper) given your description above.

Having said all that, in reference to your question #1, I would not switch off model binder validation. Let that performance the validation on your view models as normal. Map your view models to your domain model classes. Then feel free to perform an additional layer of business object validation for your domain model. You may not even doing this validation in the MVC project - this might be encapsulated in a business layer that you have somewhere else in your app.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.