简体   繁体   中英

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

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;
    }

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