ASP.NET MVC Model Binder for Generic Type

前端 未结 1 1598
轻奢々
轻奢々 2020-12-01 09:58

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

public class MyType

Is there any way t

相关标签:
1条回答
  • 2020-12-01 10:25

    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;
        }
    
    0 讨论(0)
提交回复
热议问题