Created
April 25, 2012 14:56
-
-
Save fjeldstad/2490355 to your computer and use it in GitHub Desktop.
ModelStateDictionary.Simplify extension method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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