简体   繁体   中英

asp.net mvc is it possible to use two custom model binders?

So I have one custom model binder that inherits from DefaultModelBinder, where I am overriding the BindProperty() method to handle a type of field we've created.

I also have one controller that we'd like to override BindModel() on, since we're handling an object in session for multiple views with that controller.

So I have CustomModelBinder : DefaultModelBinder, and then in the class where we override BindModel() i have that inheriting from CustomModelBinder. SpecialModelBinder: CustomModelBinder

But I have set a breakpoint in our override of BindProperty() in CustomModelBinder, and this never gets hit when using the controller that is also overriding BindModel().

Can I not inherit like this? What's happening here?

Thank You!

edit:

in global.asax:

ModelBinders.Binders.Add(typeof(ClassA), new SpecialModelBinder());
ModelBinders.Binders.Add(typeof(ClassB), new CustomModelBinder());
ModelBinders.Binders.Add(typeof(ClassC), new CustomModelBinder());
ModelBinders.Binders.Add(typeof(ClassD), new CustomModelBinder());

public class CustomModelBinder : DefaultModelBinder
{
    // this will be hit in controllers that handle classes B, C, and D, but will not be hit in controller that handles ClassA
    protected override void BindProperty(...){}
}

public class SpecialModelBinder : CustomModelBinder
{  
    // this will be hit when working in controller that handles ClassA only
    public override object BindModel(...){}
}

I recreated the scenario you described in an empty MVC application, and wasn't able to replicate the situation you describe here. I had no problem subclassing SpecialModelBinder from CustomModelBinder and hitting both breakpoints in all classes. Is there any other informaiton you can provide that might illuminate a solution? As you describe it here, there should be no issue with hitting both breakpoints for ClassA and only the BindProperty method for B, C and D.

Scenarios I tried: 1) Edit ClassA . Result: BindModel() on SpecialModelBinder called and BindProperty() on CustomModelBinder called for each property on the class; 2) Edit ClassB (or C or D). Result: BindProperty() on CustomModelBinder called for each property on the class.

Is there anything else in your Application_Start() method in Global.asax , other than the Area and Route registration calls?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM