[MVC 3] ModelState ModelErrorCollection Debug–Extension Method


In the last i described a way of using a static method to obtain which model field is causing your ModelState to be invalid. My good friend Shaw Young said that a Extension Method would be another way of doing this. And thinking of it, it makes more sense and a better and cleaner implementation.

So here is that piece of code again:

if (ModelState.IsValid)
{

  //—Your code here
}
else {
    Debug.ModelStateErrors( ModelState);
    ModelState.ModelStateErrors();
}

So now instead of a Debug.ModelStateErrors, there is a Extension Method ModelStateErrors referenced by the object itself.

And here is the code:

public static void ModelStateErrors (this ModelStateDictionary modelState)
{
    var errors = modelState.Where(a => a.Value.Errors.Count > 0)
        .Select(b => new { b.Key, b.Value.Errors })
        .ToArray();

    foreach (var modelStateErrors in errors)
    {
        int count = modelStateErrors.Errors.Count();
        System.Diagnostics.Debug.WriteLine("...Errored When Binding.",        
        modelStateErrors.Key.ToString());

    }

}

There you are! The only difference is the implementation of the static method itself. The actual code is the same.

Enhanced by Zemanta

2 thoughts on “[MVC 3] ModelState ModelErrorCollection Debug–Extension Method

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s