zoukankan      html  css  js  c++  java
  • MVC 为反射出来的object执行模型绑定

    解决方案

    新建ControllerBase类,然后定义如下方法:

    protected internal bool MyTryUpdateModel<TModel>(TModel model, string prefix, string[] includeProperties, string[] excludeProperties, IValueProvider valueProvider) where TModel : class
    {
         if (model == null)
         {
              throw new ArgumentNullException("model");
         }
         if (valueProvider == null)
         {
              throw new ArgumentNullException("valueProvider");
         }
    
         Predicate<string> propertyFilter = propertyName => IsPropertyAllowed(propertyName, includeProperties, excludeProperties);
         IModelBinder binder = Binders.GetBinder(model.GetType());
    
         ModelBindingContext bindingContext = new ModelBindingContext()
         {
             ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()),
             ModelName = prefix,
             ModelState = ModelState,
             PropertyFilter = propertyFilter,
             ValueProvider = valueProvider
         };
         binder.BindModel(ControllerContext, bindingContext);
         return ModelState.IsValid;
    }
    
    internal static bool IsPropertyAllowed(string propertyName, ICollection<string> includeProperties, ICollection<string> excludeProperties)
    {
         // We allow a property to be bound if its both in the include list AND not in the exclude list.
         // An empty include list implies all properties are allowed.
         // An empty exclude list implies no properties are disallowed.
         bool includeProperty = (includeProperties == null) || (includeProperties.Count == 0) || includeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);
         bool excludeProperty = (excludeProperties != null) && excludeProperties.Contains(propertyName, StringComparer.OrdinalIgnoreCase);
         return includeProperty && !excludeProperty;
    }
    

    以上两个方法都来自MVC源码,仅将对Type的获取地方做了修改,原为typeof(TModel),现改为model.GetType()。

    使用方法

    使用方法同TryUpdateModel()。

  • 相关阅读:
    Vim作者创造新编程语言Zimbu
    Google Maps API编程资源大全
    好网收集的地址
    三种模拟自动登录和提交POST信息的实现方法
    解析VMware三种网络连接方式
    PostgreSQL 创建帐号,数据库,权限
    LINUX目录详解
    Linux流媒体服务器安装配置
    用RAMDISK来提高PostgreSQL访问速度
    PostgreSQL 集群复制方案之使用pgq和londiste工具包
  • 原文地址:https://www.cnblogs.com/dotnetmonkey/p/8676903.html
Copyright © 2011-2022 走看看