Skip to content

Instantly share code, notes, and snippets.

@elizabeth-young
Created August 10, 2016 07:46
Show Gist options
  • Save elizabeth-young/beea49d68a203b1aa46c7cc93874606e to your computer and use it in GitHub Desktop.
Save elizabeth-young/beea49d68a203b1aa46c7cc93874606e to your computer and use it in GitHub Desktop.
Mvc ModelState extensions to get error list from ModelState
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