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
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With