Creating a custom ModelValidatorProvider in ASP.NET MVC

The validation framework of ASP.NET MVC is designed in such a way that it could be easily customizable/extensible at many points. The validation system is built using lot of classes and it's quite difficult to understand all of them. Sadly, there is no much documentation available in MSDN to help out. As default, the validations are performed by decorating models and properties with validation attributes. These validation attributes are available in a separate assembly called System.ComponentModel.DataAnnotations.

Sometimes, in applications we need to apply or perform validations in different ways. For ex. say we want to store the validation rules for a model in database or in xml files. In these cases, we have to go for implementing custom validation solutions and for that understanding the built-in validation model is trivial.

In this article, we are going to see how we can create a custom ModelValidatorProvider that validates models based upon the rules specified in the xml files and works side-by-side with the other built-in validator providers.

Continue Reading

Simplifying html generation in code using Razor templates

In ASP.NET MVC, we can construct html from code using the TagBuilder class. The built-in html helpers uses the TagBuilder class to generate textboxes, checkboxes and other html stuff. Generating html from code is not flexible because every time we need to alter the html we have to go for recompilation.

We all know that, the built-in ValidationSummary html helper displays the validation errors as an unordered list but in some cases we need to customize the way in which the errors are being displayed, say as a table instead of list. The ValidationSummary method creates the list inside the code and we can't customize it. All we could do is create our own custom helper to display the errors as a table.

It would be nice if we could pass the html structure or template that controls the way in which the validation errors are being displayed to the user to the helper from the view and that's what the subject of this post.

Continue Reading