2011-11-28 37 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) 
{ 
    ... 
} 
相關問題