MVC网站开发:自定义扩展方法ModelStateExtension获取ModelState中的错误信息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/song_jiang_long/article/details/54382455

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;


namespace Rw.Web.Core.Extension
{
    public static class ModelStateExtension
    {

        /// <summary>
        /// 获取模型绑定中的ErrMsg
        /// </summary>
        /// <param name="msDictionary"></param>
        /// <returns></returns>
        public static string GetErrMsg(this ModelStateDictionary msDictionary)
        {
            if (msDictionary.IsValid || !msDictionary.Any()) return "";
            foreach (string key in msDictionary.Keys)
            {
                ModelState tempModelState = msDictionary[key];
                if (tempModelState.Errors.Any())
                {
                    var firstOrDefault = tempModelState.Errors.FirstOrDefault();
                    if (firstOrDefault != null)
                        return firstOrDefault.ErrorMessage;
                }
            }
            return "";
        }
    }
}


猜你喜欢

转载自blog.csdn.net/song_jiang_long/article/details/54382455