I wrote a couple of posts on using the Enterprise Library Validation Application Block with the ASP.NET MVC Framework:
Some of the details have changed in the more recent ASP.NET MVC Beta, but the concept of copying any errors found by the Validation Application Block to the Controller’s ModelState to display errors stays the same.
ASP.NET MVC Validation – Simple Example
Let’s take a simple example of using the Validation Application Block’s Facade Class to validate an instance of Customer in the CustomerController’s Create Action:
public ActionResult Create(FormCollection form)
// Bind Customer to Form Values
var results = Validation.Validate(customer);
If the customer instance is invalid according to our validation rules, we need to add the errors from the ValidationResults instance to the ModelState as shown above. The AddModelErrorsFrom method is an extension method created to simply the process.
Add an Extension Method to ModelStateDictionary
One can tackle the problem of copying those errors in many ways, and one easy solution is to create a quick Extension Method on ModelStateDictionary that essentially iterates through all the errors in the ValidationResults instance and adds those errors to the CustomerController’s ModelState Property. The AddModelErrorsFrom is an Extension Method defined as such:
public static void AddModelErrorsFrom(this ModelStateDictionary dictionary,
foreach (var error in results)
This isn’t rocket science, but it sure does simplify the process of copying the errors vs. a private method as seen in other examples, including my own, on the Internet. It also makes the code a lot easier to read.
I talked about this extension method at the ASP.NET MVC Firestarter Event in Tampa, Florida for those who attended.
Hope it helps,