Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

ASP.NET MVC – Using Extension Method to Add Validation Application Block Errors to Controller’s ModelState

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:


 



[AcceptVerbs(HttpVerbs.Post)]


public ActionResult Create(FormCollection form)


{


    // …


 


    // Bind Customer to Form Values


    UpdateModel<ICustomerFormBindable>(customer);


 


    // Validate


    var results = Validation.Validate(customer);


    if (!results.IsValid)


    {


        ModelState.AddModelErrorsFrom(results);


        return View(form);


    }


 


    // …


}


 


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,


                                            ValidationResults results)


{


    foreach (var error in results)


            dictionary.AddModelError(error.Key, error.Message);


}


 


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.


 


 


Conclusion


I talked about this extension method at the ASP.NET MVC Firestarter Event in Tampa, Florida for those who attended.


Hope it helps,


David Hayden


 


Recent Posts:



 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

One Response to ASP.NET MVC – Using Extension Method to Add Validation Application Block Errors to Controller’s ModelState

  1. Jarda Jirava says:

    Hi,
    I made the same version like you, but needs and overloaded method which has a prefix parameter.
    if (prefix == null) {
    prefix = string.Empty;
    }
    if ((!string.IsNullOrEmpty(prefix)) && (!prefix.EndsWith(“.”))) {
    prefix += “.”;
    }
    foreach (var validationResult in results) {
    state.AddModelError(prefix + validationResult.Key, validationResult.Message);
    }
    HTH
    –J.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>