Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

ModelStateExtensions.cs

using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace Nop.Web.Framework.Mvc.ModelBinding;

/// 
/// ModelState extensions
/// 
public static class ModelStateExtensions
{
    private static Dictionary SerializeModelState(ModelStateEntry modelState)
    {
        var errors = new List();
        for (var i = 0; i < modelState.Errors.Count; i++)
        {
            var modelError = modelState.Errors[i];

            if (!string.IsNullOrEmpty(modelError.ErrorMessage))
            {
                errors.Add(modelError.ErrorMessage);
            }
        }

        var dictionary = new Dictionary
        {
            ["errors"] = errors.ToArray()
        };
        return dictionary;
    }

    /// 
    /// Serialize errors
    /// 
    /// ModelStateDictionary
    /// Result
    public static object SerializeErrors(this ModelStateDictionary modelStateDictionary)
    {
        return modelStateDictionary.Where(entry => entry.Value.Errors.Any())
            .ToDictionary(entry => entry.Key, entry => SerializeModelState(entry.Value));
    }
}