[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

[MVC 3] ModelState ModelErrorCollection Debug


UPDATE: Dan Kendall kindly done a gist of the code which can be found here if you need it which is related to this post:

https://gist.github.com/3699804

We all use the ModelState.IsValid before we commit any changes to our Entity Framework ObjectContext to update our data source. But what is ModelState.IsValid? Well basically ModelState says…

“Yes, all models have binded successfully from the view”

But what happens when we the ModelState is NOT valid. Well, I  have a little static method So you can write to the Output window to see what the property name is, so you can fix it quickly.

if (ModelState.IsValid)
{
   ///—- Your code.
}
else {
    Debug.ModelStateErrors( ModelState);

}

Now my method, Debug.ModelStateErrors consists of an Anon Type which i use a LINQ to abstract the ModelErrorCollection from the ModelState. I then print out the Key from the Dictionary to the Output window.  Example on the 2nd image which is property.PropertyType is the model field.

#if DEBUG
       /// <summary> 
 /// Output the properties which are causing the issues when 
 /// the model is binding. 
 /// </summary> public static void ModelStateErrors (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)
            {
                 System.Diagnostics.Debug.WriteLine("...Errored When Binding.",                                  modelStateErrors.Key.ToString());

            }

        }
#endif #endregion 

Capture

Enhanced by Zemanta