• 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()。

  • 相关阅读:
    洛谷 P3366 【模板】最小生成树
    洛谷 P2820 局域网
    一本通【例4-10】最优布线问题
    洛谷 P1546 最短网络 Agri-Net
    图论模板
    洛谷 AT667 【天下一人力比較】
    刷题记录
    洛谷P1553 数字翻转(升级版)
    tornado硬件管理系统-网络与磁盘的实现(7)
    tornado硬件管理系统-内存与swap的实现(6)
  • 原文地址:https://www.cnblogs.com/dotnetmonkey/p/8676903.html
Copyright © 2020-2023  润新知