DataAnnotations vs IDataErrorInfo
Pros and Cons of both? Benefits of one over the other? (especially related to MVC)
DataAnnotations vs IDataErrorInfo
Pros and Cons of both? Benefits of one over the other? (especially related to MVC)
Looks like DataAnnotations are getting official support in MVC 2.0. Scott Guthrie published a good article on doing model validation in 2.0 using DataAnnotations. Given that the team seems headed this direction, you might consider that a vote in its favor.
DataAnnotations are easier to implement, and getting directly support in MVC 2.0.
However, IDataErrorInfo
allows you do to more complex validation (ie: validation that spawns multiple properties, etc).
The two can be mixed, and used together, however. There is nothing stopping you from implementing both techniques.
Late entry to the discussion as I do not want to start a new question. Where I am coming from is to determine the best practice to apply to a medium size ASP.NET MVC project.
Let me first summarise our options :-
1) IDataErrorInfo is simple to implement. All you need is to derive IDataErrorInfo in your Model class. The catch is that you are letting your model binding to be enforcing your business rules. Business rules should be enforced by the Model. The other catch for IDataErrorInfo (and likewise for DataAnnotations) is that (paraphrasing from Steven Sanderson's book it could not report multiple errors relating to a single property or multiple errors relating to the whle object model.
2) DataAnnotation to me, is like a schema check (validation). This is the first check that your application should do. However (IMHO), it is not suited to implement your business rules.
3) Implement your own ModelBinder. Although this can be done but seriously speaking, the usage of ModelBinder is to parse and bind your data to your model and not to perform complicated validations and business rule checks. I would leave the Business rules check to be implemented in your Model/Domain layer.
4) Roll your own - Validating with a service layer (see this. The example shown has its advantage of decoupling from the Controller and Model State using an interface class. Another option is to throw an appropriate exception from your model layer. The latter option is useful when you implement your service layer in a separate application (e.g a WCF application).
What do you think? For a medium to large size project, which of the above options have you used (or intend to adopt) and why?
Cheers