ASP.NET MVC How to convert ModelState errors to json

前端 未结 13 2053
余生分开走
余生分开走 2020-12-04 05:24

How do you get a list of all ModelState error messages? I found this code to get all the keys: ( Returning a list of keys with ModelState errors)

var errorK         


        
相关标签:
13条回答
  • 2020-12-04 05:57

    ToDictionary is an Enumerable extension found in System.Linq packaged in the System.Web.Extensions dll http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary.aspx. Here's what the complete class looks like for me.

    using System.Collections;
    using System.Web.Mvc;
    using System.Linq;
    
    namespace MyNamespace
    {
        public static class ModelStateExtensions
        {
            public static IEnumerable Errors(this ModelStateDictionary modelState)
            {
                if (!modelState.IsValid)
                {
                    return modelState.ToDictionary(kvp => kvp.Key,
                        kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()).Where(m => m.Value.Count() > 0);
                }
                return null;
            }
    
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题