• 使用System.Web 中的模型绑定


        需要用到这个是因为在asp.net Web Form 中使用ashx 的时候没有一个好的模型绑定.所以我找到了dll 中自带的.并且将他封装了一下

            代码如下:

        public class ModelBinder
        {
            public static BinderResultModel<T> BindModel<T>() where T : new()
            {
                var dicState = new ModelStateDictionary();
                ModelBindingExecutionContext context = new ModelBindingExecutionContext(new HttpContextWrapper(HttpContext.Current), dicState);
                ModelBindingContext bindingContext = new ModelBindingContext()
                {
                    ModelBinderProviders = ModelBinderProviders.Providers,
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => Activator.CreateInstance<T>(), typeof(T)),
                    ModelState = dicState,
                    ValueProvider = new NameValueCollectionValueProvider(context.HttpContext.Request.Params, CultureInfo.CurrentCulture),
                    ValidateRequest = true,
                };
                bindingContext.ValidationNode.ValidateAllProperties = true;
                if (ModelBinders.Binders.DefaultBinder.BindModel(context, bindingContext))
                {
                    return new BinderResultModel<T>((T)bindingContext.Model, dicState);
                }
                return BinderResultModel<T>.NULL;
            }
            public class BinderResultModel<T> where T : new()
            {
                public static BinderResultModel<T> NULL
                {
                    get
                    {
                        return new BinderResultModel<T>(default(T), null, "返回空对象");
                    }
                }
                public bool IsValid { get; }
                public T Data { get; }
                public string ErrorMessage { get { return _errorMsg; } private set { _errorMsg = value; } }
                private ModelStateDictionary _modelStateDic;
                private string _errorMsg = string.Empty;
                #region 构造函数
                public BinderResultModel(T t, ModelStateDictionary modelStateDic)
                {
                    IsValid = false;
                    Data = t;
                    _modelStateDic = modelStateDic;
                    if (_modelStateDic != null)
                    {
                        IsValid = _modelStateDic.IsValid;
                    }
                    _errorMsg = GetErrorMessage();
                }
                public BinderResultModel(T t, ModelStateDictionary modelStateDic, string errorMsg) : this(t, modelStateDic)
                {
                    _errorMsg = errorMsg;
                }
                #endregion
                #region 私有函数
    
                private string GetErrorMessage()
                {
                    if (_modelStateDic is null)
                    {
                        return string.Empty;
                    }
                    StringBuilder builder = new StringBuilder();
                    foreach (var state in _modelStateDic)
                    {
                        foreach (var error in state.Value.Errors)
                        {
                            builder.Append(error.ErrorMessage);
                        }
                        builder.AppendLine();
                    }
                    return builder.ToString();
                }
                #endregion
            }
        }

      测试时使用的类:

      

        class Person
        {
            // [BindingBehavior(BindingBehavior.Never)]
            //[Required(ErrorMessage = "姓名为必填")]
            [Display(Name = "姓名")]
            [MinLength(20, ErrorMessage = "最小长度为20")]
            [RegularExpression("/^/d$/", ErrorMessage = "不满足正则表达式")]
            public string Name { get; set; }
            public int Age { get; set; }
            [BindingBehavior(BindingBehavior.Never)]//表示从不绑定此属性
            public List<int> List { get; set; }
            public Dictionary<string, string> Dics { get; set; }
            [Required(ErrorMessage = "ma为必须")]
            public Man ma { get; set; }
        }
        class Man
        {
            [Required(ErrorMessage = "666666666666")]
            public string MMM { get; set; }
        }

     使用方式:

                var result = ModelBinder.BindModel<Person>();
                if (result.IsValid)
                {
                    //绑定成功,并且校验通过  dosomething
                }
                else
                {
                    //do something
                }
  • 相关阅读:
    OpenCV学习笔记(一)
    scrapy学习笔记一
    Mac上使用selenium自动运行chrome
    【js Utils】web前端工具帮助类kikyoUtils
    【jq 分享】伪微信分享
    【Winform 动图】winform窗体显示动图
    【 Base<T> 】IBaseDao 和 IBaseService 通用 基类 实现
    【js 是否手机】JavaScript判读当前是否是手机端
    【Spring helper】在controller和service间添加业务处理helper类
    【 spring resources 】maven项目resources文件夹,配置文件的spring加载方式
  • 原文地址:https://www.cnblogs.com/student-note/p/12466651.html
Copyright © 2020-2023  润新知