如何获得参数的属性,我试图绑定到IModelBinder
本文关键字:绑定 IModelBinder 何获得 参数 属性 | 更新日期: 2023-09-27 18:15:53
是否有办法从IModelBinder.BindModel()
内部访问当前正在处理的控制器动作参数的属性?
特别是,我正在编写一个绑定请求数据到任意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));
}
}
我怀疑在请求工作流中可能有另一个更合适的点,我可以在那里提供属性值。
了解如何使用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)
{
...
}