[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

2 thoughts on “[MVC 3] ModelState ModelErrorCollection Debug

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