Model binder at controller level

1k views Asked by At

Is there a way to implement the following:

// Model.cs

[ModelBinder(typeof(DefaultModelBinder))]
public class Model
{
}

public class DefaultModelBinder: IModelBinder
{
}

public class CustomModelBinder: DefaultModelBinder
{
}

// Controller1.cs

public class Controller1: Controller
{
    public virtual ActionResult Method(Model model)
    {
    }
}

// Controller2.cs

[ModelBinder(typeof(Model), typeof(CustomModelBinder))] // imaginary attribute
public class Controller2: Controller
{
    public virtual ActionResult Method(Model model)
    {
    }
}

I am aware of the ModelBinder at action level, however given a bunch of actions it does not follow DRY principle, as the whole controller is to use the CustomModelBinder.

Thanks.

1

There are 1 answers

5
Mihai Tibrea On

Is this what you are looking for ?

using IModelBinder = System.Web.Mvc.IModelBinder;
using ModelBindingContext = System.Web.Mvc.ModelBindingContext;

public class CustomeModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        //your code here
    }
}