Model Binding
Model binding(绑定)简单来说就是通过遍历ValueProvider(值提供者)获取的数据对Action参数进行赋值.
在学习本篇教程,应对model binding有基础了解。
DefaultPropertyBindingPredicateProvider
DefaultPropertyBindingPredicateProvider:提供一种基于表达式的方法来提供包括的属性。
public class DefaultPropertyBindingPredicateProvider<TModel> : IPropertyBindingPredicateProvider where TModel : class { public DefaultPropertyBindingPredicateProvider(); public virtual string Prefix { get; } public virtual Func<ModelBindingContext, string, bool> PropertyFilter { get; } public virtual IEnumerable<Expression<Func<TModel, object>>> PropertyIncludeExpressions { get; } }
这个类有三个属性:
Prefix 表示前缀名
PropertyFilter :属性过滤
PropertyIncludeExpressions :属性包括表达式来看下怎么用实例代码
private class ExcludeUserPropertiesAtParameter : DefaultPropertyBindingPredicateProvider<User> { Func<ModelBindingContext, string, bool> _defaultFilter1 = (context, propertyName) => false; public ExcludeUserPropertiesAtParameter() { } public override string Prefix { get { return "user"; } } public override IEnumerable<Expression<Func<User, object>>> PropertyIncludeExpressions { get { yield return m => m.RegisterationMonth; yield return m => m.UserName; } } }
控制器
public class BindAttributeController : Controller { public User EchoUser([Bind(typeof(ExcludeUserPropertiesAtParameter))] User user) { return user; }
User实体
public class User { [Required] public int Id { get; set; } public int Key { get; set; } [Required] public string RegisterationMonth { get; set; } public string UserName { get; set; } public Address Address { get; set; } }
Prefix 前缀名是user,也就是说请求id必需加上user作为前缀
PropertyIncludeExpressions:属性包括:
get
{ yield return m => m.RegisterationMonth; yield return m => m.UserName; }
表示:支队这个属性进行赋值。
我们来看看PropertyFilter作用
private class ExcludeUserPropertiesAtParameter : DefaultPropertyBindingPredicateProvider<User> { Func<ModelBindingContext, string, bool> _defaultFilter1 = (context, propertyName) => false; public ExcludeUserPropertiesAtParameter() { } public override string Prefix { get { return "user"; } } public override Func<ModelBindingContext, string, bool> PropertyFilter { get { return _defaultFilter1; } } }
_defaultFilter1 表达式一直返回false
全部没有赋值,
PropertyFilter:
PropertyIncludeExpressions等于null propertyFilter 将默认返回true. FromQueryAttribute
FromRouteAttributeFromFormAttribute
时间: 2024-10-21 18:37:28