在MVC3 (.Net)中,可以在Controller方法的方法签名中对参数类型设置绑定属性:
[HttpPost]
public ActionResult Edit([Bind(Exclude = "Name")]User user)
{
...
}我写了一些定制的ModelBinders。如果能够根据参数类型上设置的属性来影响他们的行为,那就太好了,如下所示:
[HttpPost]
public ActionResult Edit([CustomModelBinderSettings(DoCustomThing = "True")]User user)
{
...
}但是,我似乎找不到恢复属性数据的方法。这个是可能的吗?
编辑
我正在尝试从自定义的AttributeData中访问ModelBinder。在下面的示例中,“设置”始终为空。
public class TestBinder : DefaultModelBinder {
public override object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext) {
//Try and get attribute from ModelType
var settings = (CustomModelBinderSettingsAttribute)
TypeDescriptor.GetAttributes(bindingContext.ModelType)[typeof(CustomModelBinderSettingsAttribute)];
...谢谢你的帮助。
发布于 2012-04-01 05:15:45
答:不可能:
我深入研究了MVC源代码,最终发现ControllorActionInvoker类显式地从Action参数访问bind属性,并在bindingContext的一个属性上设置它们。如果不覆盖或重写MVC基础结构的大部分,就不可能从ModelBinder访问添加到Action参数的属性。
但是,可以使用ViewModel post中所示的代码检索设置在LukLeds上的属性:
var attr = ("GetTypeDescriptor(controllerContext, bindingContext).GetAttributes()[typeof(BindAttribute)];唉,这不是我在这件事上打算做的事,但现在必须这样做。
发布于 2012-03-30 22:30:06
为了从您的DoCustomThing中访问CustomModelBinderAttribute属性的值,您不需要做任何事情。您在哪里试图读取不可用的DoCustomThing值?
public class CustomModelBinderSettingsAttribute : CustomModelBinderAttribute
{
public string DoCustomThing { get; set; }
public override IModelBinder GetBinder()
{
// Pass the value of DoCustomThing to the custom model binder instance.
MyCustomizableModelBinder binder = new MyCustomizableModelBinder(this.DoCustomThing);
return binder;
}
}发布于 2014-10-09 20:44:27
如果您有(或创建新的) AuthorizeAttribute (filter属性),它可以将filterContext.ActionDescriptor (您的操作)存储在HttpContext.Current.Items中,然后在ModelBinder中检索该值。有了ActionDescriptor,您就可以通过bindingContext.ModelName找到所需的参数,并检查属性是否存在。
要注意的事情:
https://stackoverflow.com/questions/9951068
复制相似问题