首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用属性影响MVC ModelBinders

使用属性影响MVC ModelBinders
EN

Stack Overflow用户
提问于 2012-03-30 22:14:10
回答 5查看 1.4K关注 0票数 1

在MVC3 (.Net)中,可以在Controller方法的方法签名中对参数类型设置绑定属性:

代码语言:javascript
复制
[HttpPost]
public ActionResult Edit([Bind(Exclude = "Name")]User user)
{
   ...
}

我写了一些定制的ModelBinders。如果能够根据参数类型上设置的属性来影响他们的行为,那就太好了,如下所示:

代码语言:javascript
复制
[HttpPost]
public ActionResult Edit([CustomModelBinderSettings(DoCustomThing = "True")]User user)
{
   ...
}

但是,我似乎找不到恢复属性数据的方法。这个是可能的吗?

编辑

我正在尝试从自定义的AttributeData中访问ModelBinder。在下面的示例中,“设置”始终为空。

代码语言:javascript
复制
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)];

            ...

谢谢你的帮助。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2012-04-01 05:15:45

答:不可能:

我深入研究了MVC源代码,最终发现ControllorActionInvoker类显式地从Action参数访问bind属性,并在bindingContext的一个属性上设置它们。如果不覆盖或重写MVC基础结构的大部分,就不可能从ModelBinder访问添加到Action参数的属性。

但是,可以使用ViewModel post中所示的代码检索设置在LukLeds上的属性:

代码语言:javascript
复制
var attr = ("GetTypeDescriptor(controllerContext, bindingContext).GetAttributes()[typeof(BindAttribute)];

唉,这不是我在这件事上打算做的事,但现在必须这样做。

票数 0
EN

Stack Overflow用户

发布于 2012-03-30 22:30:06

为了从您的DoCustomThing中访问CustomModelBinderAttribute属性的值,您不需要做任何事情。您在哪里试图读取不可用的DoCustomThing值?

代码语言:javascript
复制
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;
    }
}
票数 0
EN

Stack Overflow用户

发布于 2014-10-09 20:44:27

如果您有(或创建新的) AuthorizeAttribute (filter属性),它可以将filterContext.ActionDescriptor (您的操作)存储在HttpContext.Current.Items中,然后在ModelBinder中检索该值。有了ActionDescriptor,您就可以通过bindingContext.ModelName找到所需的参数,并检查属性是否存在。

要注意的事情:

  • ModelBinder不绑定到已执行的操作
  • 使用ControllerContext,您可以调用ActionName,但不需要调用实际的方法(可能有多个重载的参数)
  • AuthorizeFilter在ModelBinder之前调用,普通ActionFilter在ModelBinder之后调用
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9951068

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档