C# 如何在IModelBinder中获取我试图绑定到的参数的属性?
是否有方法从C# 如何在IModelBinder中获取我试图绑定到的参数的属性?,c#,asp.net-mvc-3,C#,Asp.net Mvc 3,是否有方法从IModelBinder.BindModel()中访问当前正在处理的控制器操作参数的属性 特别是,我正在编写一个绑定器,用于将请求数据绑定到任意Enum类型(指定为模型绑定器的模板参数),并希望为每个控制器操作参数指定一个HTTP请求值的名称,以便从中获取Enum值 例如: public ViewResult ListProjects([ParseFrom("jobListFilter")] JobListFilter filter) { ... } 模型活页夹: publ
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));
}
}
public类EnumBinder:IModelBinder
{
公共对象绑定模型(ControllerContext ControllerContext,
ModelBindingContext(绑定上下文)
{
HttpRequestBase请求=controllerContext.HttpContext.request;
//获取action方法参数的ParseFrom属性
//从属性中,获取要分析的表单字段名
//
字符串formField=getFormFieldNameToParsed();
返回ConvertToEnum(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)
{
...
}