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

posted @ 2018-03-30 16:20  zhaok  阅读(137)  评论(0编辑  收藏  举报