.netasp.net-mvcasp.net-mvc-3model-bindingmodelbinders

Affecting MVC ModelBinders with Attributes


In MVC3 (.Net) it is possible to set a Bind Attribute on a parameter Type in the method signature for a Controller method:

[HttpPost]
public ActionResult Edit([Bind(Exclude = "Name")]User user)
{
   ...
}

I have written some Custom ModelBinders. It would be nice to be able to affect their behavior based on attributes set on a parameter Type, like so:

[HttpPost]
public ActionResult Edit([CustomModelBinderSettings(DoCustomThing = "True")]User user)
{
   ...
}

However, I can't seem to find a way to recover the attribute data. Is this possible?


Edit

I am trying to access the AttributeData from within a custom ModelBinder. In the example below "settings" is always null

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)];

            ...

Thanks for any help.


Solution

  • Answer: not possible :(

    I stepped through the MVC source code, and eventually found that the ControllorActionInvoker class explicitly accesses the bind attribute from the Action Method parameters, and sets them on a property of the bindingContext. Without overriding or rewriting large parts of the MVC infrastructure, it is not possible for attributes added to Action Parameters to be accessed from a ModelBinder.

    However, it is possible to retrieve attributes set on a ViewModel using the code illustrated in LukLeds post:

    var attr = ("GetTypeDescriptor(controllerContext, bindingContext).GetAttributes()[typeof(BindAttribute)];
    

    Alas, that is not what I set out to do in this case, but it will have to do for now.