Monday, February 21, 2011

Retrieving Errors From the .NET MVC ModelState

There's good reason to write extension methods that help adding errors to the .NET MVC ModelState Dictionary, and the Microsoft tutorials present some reasonable, readily-available solutions for this. But you might also desire to get back those errors in the form in which they were added in the first place, and for that it's a little bit trickier. Using the RuleViolation class pattern provided on the asp.net website, the code below uses LINQ query syntax with outer range variables to handle the SelectMany query projection into an IEnumerable<RuleRiolation> collection object.

public static IEnumerable<RuleViolation> GetRuleViolations(this ModelStateDictionary modelState)
        {
            var violations = from vals in modelState
                             from errors in vals.Value.Errors
                             where vals.Value.Errors.Count > 0
                             select new RuleViolation(errors.ErrorMessage, vals.Key);

            return violations;
        }