Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Model Binder for Generic Type

Is it possible to create a model binder for a generic type? For example, if I have a type

public class MyType<T>

Is there any way to create a custom model binder that will work for any type of MyType?

Thanks, Nathan

like image 953
Nathan Roe Avatar asked Sep 28 '09 13:09

Nathan Roe


People also ask

What are model binders in ASP.NET MVC?

Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.

Can we create custom model binder?

We can apply custom model binder using ModelBinder attribute by defining attributes on action method or model. If we are using this method (applying attribute on action method), we need to define this attribute on every action methods those want use this custom binding.

How data binding can be used in ASP.NET MVC?

ASP.NET MVC model binder allows you to map Http Request data with the model. Http Request data means when a user makes a request with form data from the browser to a Controller, at that time, Model binder works as a middleman to map the incoming HTTP request with Controller action method.


1 Answers

Create a modelbinder, override BindModel, check the type and do what you need to do

public class MyModelBinder
    : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

         if (HasGenericTypeBase(bindingContext.ModelType, typeof(MyType<>)) { 
             // do your thing
         }
         return base.BindModel(controllerContext, bindingContext);
    }
}

Set your model binder to the default in the global.asax

protected void Application_Start() {

        // Model Binder for My Type
        ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    }

checks for matching generic base

    private bool HasGenericTypeBase(Type type, Type genericType)
    {
        while (type != typeof(object))
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
            type = type.BaseType;
        }

        return false;
    }
like image 110
Anthony Johnston Avatar answered Sep 25 '22 12:09

Anthony Johnston