Skip to content

Instantly share code, notes, and snippets.

@fjeldstad
Created April 25, 2012 14:56
Show Gist options
  • Save fjeldstad/2490355 to your computer and use it in GitHub Desktop.
Save fjeldstad/2490355 to your computer and use it in GitHub Desktop.
ModelStateDictionary.Simplify extension method
/// <summary>
/// Simplifies the structure of a ModelStateDictionary instance to a "key => [ "error1", "error2", ... "errorN" ]" dictionary.
/// Also removes entries with no error messages.
/// </summary>
/// <param name="modelState"></param>
/// <returns></returns>
public static Dictionary<string, string[]> Simplify(this ModelStateDictionary modelState)
{
return modelState.ToDictionary(
entry => entry.Key,
entry => entry.Value.Errors
.Where(error => !string.IsNullOrEmpty(error.ErrorMessage) || error.Exception != null)
.Select(error => !string.IsNullOrEmpty(error.ErrorMessage) ? error.ErrorMessage : error.Exception.Message).ToArray())
.Where(entry => entry.Value.Any())
.ToDictionary(entry => entry.Key, entry => entry.Value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment