ASP.NET MVC Model Binder for Generic Type

核能气质少年 提交于 2019-12-17 09:33:50

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/1487005/asp-net-mvc-model-binder-for-generic-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!