Created
August 10, 2016 07:46
-
-
Save elizabeth-young/beea49d68a203b1aa46c7cc93874606e to your computer and use it in GitHub Desktop.
Mvc ModelState extensions to get error list from ModelState
This file contains hidden or 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
using System.Collections.Generic; | |
using System.Linq; | |
usingusing System.Collections.Generic; | |
using System.Linq; | |
using System.Web.Mvc; | |
namespace Gists.Mvc.Helpers | |
{ | |
public static class ModelExtensions | |
{ | |
public static List<string> GetErrorList(this ModelStateDictionary modelState) | |
{ | |
var errorList = modelState.Values | |
.SelectMany(x => x.Errors) | |
.Select(x => x.ErrorMessage).ToList(); | |
return errorList; | |
} | |
public static Dictionary<string, List<string>> GetErrors(this ModelStateDictionary modelState) | |
{ | |
var errorList = modelState | |
.Where(x => x.Value.Errors.Count > 0) | |
.ToDictionary( | |
kvp => kvp.Key, | |
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToList() | |
); | |
return errorList; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment