2011-11-28 36 views
3

有没有办法从IModelBinder.BindModel()中访问当前正在处理的控制器动作参数的属性?如何获取我想要绑定到IModelBinder的参数的属性?

特别是,我正在为绑定请求数据写入任意Enum类型的绑定器(指定为模型绑定器的模板参数),我想为每个控制器指定要为其使用的动作参数绑定HTTP请求值的名称以从中获取Enum值。

实施例:

public ViewResult ListProjects([ParseFrom("jobListFilter")] JobListFilter filter) 
{ 
    ... 
} 

和模型粘合剂:

public class EnumBinder<T> : IModelBinder 
{ 
    public object BindModel(ControllerContext controllerContext, 
          ModelBindingContext bindingContext) 
    { 
     HttpRequestBase request = controllerContext.HttpContext.Request; 

     // Get the ParseFrom attribute of the action method parameter 
     // From the attribute, get the FORM field name to be parsed 
     // 
     string formField = GetFormFieldNameToBeParsed(); 

     return ConvertToEnum<T>(ReadValue(formField)); 
    } 
} 

我怀疑有可能是在我将提供的属性值的请求工作流另一个更适当,点。

回答

2

发现了如何使用CustomModelBinderAttribute派生类做到这一点:

public class EnumModelBinderAttribute : CustomModelBinderAttribute 
{ 
    public string Source { get; set; } 
    public Type EnumType { get; set; } 

    public override IModelBinder GetBinder() 
    { 
     Type genericBinderType = typeof(EnumBinder<>); 
     Type binderType = genericBinderType.MakeGenericType(EnumType); 

     return (IModelBinder) Activator.CreateInstance(binderType, this.Source); 
    } 
} 

现在的操作方法是这样的:

public ViewResult ListProjects([EnumModelBinder(EnumType=typeof(JobListFilter), Source="formFieldName")] JobListFilter filter) 
{ 
    ... 
} 
相关问题