• .net 4.5 webform 提取ModelState错误信息


    .net4.5以后,webform也可以使用模型绑定和模型验证。

    user实体:

    public class User
        {
            [Required]
            [Display(Name = "用户ID")]
            public int Id { get; set; }
            [Required]
            [StringLength(20)]
            [Display(Name = "用户名")]
            public string UserName { get; set; }
            [Required]
            [StringLength(20)]
            [Display(Name = "用户密码")]
            public string PassWord { get; set; }
        }

     模型自动绑定和验证: 

    var user = new Model.User();
    var formValueProvider = new FormValueProvider(ModelBindingExecutionContext);
    TryUpdateModel(user, formValueProvider);
    //模型验证
    if (ModelState.IsValid) { Response.Write(user.UserName); }

    前台接收验证信息 

    <asp:ValidationSummary runat="server" EnableViewState="True"/>

    如果不用服务器控件,接受错误信息可以这么做

    建立名为ModelStateErrorHandler的ModelState扩展方法

    public static class ModelStateErrorHandler
        {
            /// <summary>
            /// ModelState扩展,取得Dictionary类型的错误信息
            /// </summary>
            /// <param name="errDictionary"></param>
            /// <returns>
            /// Key: 字段名
            /// Value: 字段错误信息
            /// </returns>
            public static Dictionary<string, string> GetModelErrors(this ModelStateDictionary errDictionary)
            {
                var errors = new Dictionary<string, string>();
                foreach (var pair in errDictionary.Where(k => k.Value.Errors.Count > 0))
                {
                    var er = string.Join(",", pair.Value.Errors.Select(e => e.ErrorMessage));
                    errors.Add(pair.Key, er);
                }
                return errors;
            }
            /// <summary>
            /// ModelState扩展,取得string类型的错误信息
            /// </summary>
            /// <param name="errDictionary"></param>
            /// <returns>
            /// 以|分割错误信息
            /// </returns>
            public static string GetModelErrorsString(this ModelStateDictionary errDictionary)
            {
                var errorsBuilder = new StringBuilder();
                var errors = errDictionary.GetModelErrors();
                foreach (var key in errors)
                {
                    errorsBuilder.AppendFormat("{0}:{1}|", key.Key, key.Value);
                }
                return errorsBuilder.ToString();
            }
        }

    调用:

    var errorsDictionary = ModelState.GetModelErrors();
    string jsonstr = new JavaScriptSerializer().Serialize(errorsDictionary);
    var errorsString = ModelState.GetModelErrorsString();

    在模板解析json或者字符串即可。

    .net 4.5 以后很多mvc的特性webform也可以使用了。。爽啊

  • 相关阅读:
    HDU5032 Always Cook Mushroom(树状数组&&离线)
    vue proxyTable
    vue-bus 组件通信插件
    gulp 静态资源版本控制
    js运算【按位非】~
    JS 的引用赋值与传值赋值
    手机端取消长按选中
    无刷新URL 更新
    移动端设计稿尺寸(微信端)
    4105: [Thu Summer Camp 2015]平方运算
  • 原文地址:https://www.cnblogs.com/wxb8/p/8215028.html
Copyright © 2020-2023  润新知