A Script to Print ModelState Errors and Field Names

This will write to the Output Window all the errors that are being thrown from the ModelState of an asp.net MVC Razor app.

var errors = ModelState.Where(m => m.Value.Errors.Count() > 0);
foreach (var kvp in errors)
{
    System.Diagnostics.Debug.WriteLine(string.Format("{0}:{1}", kvp.Key, kvp.Value.Errors[0].ErrorMessage));
}

The script above is helpful if/when you receive ModelState errors in your MVC Controller for no easily discernible reason. In other words, the output of the script above will print which Model fields are causing the ModelState.IsValid to return false.

Advertisements

One thought on “A Script to Print ModelState Errors and Field Names

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