Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用于泛型类型的ASP.NET MVC模型绑定器_C#_Asp.net Mvc_Generics_Model Binding - Fatal编程技术网

C# 用于泛型类型的ASP.NET MVC模型绑定器

C# 用于泛型类型的ASP.NET MVC模型绑定器,c#,asp.net-mvc,generics,model-binding,C#,Asp.net Mvc,Generics,Model Binding,是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型 public class MyType<T> 公共类MyType 有没有办法创建一个自定义的模型绑定器,可以用于任何类型的MyType 谢谢, Nathan创建一个modelbinder,重写BindModel,检查类型并执行需要执行的操作 public class MyModelBinder : DefaultModelBinder { public override object BindModel(

是否可以为泛型类型创建模型绑定器?例如,如果我有一个类型

public class MyType<T>
公共类MyType
有没有办法创建一个自定义的模型绑定器,可以用于任何类型的MyType

谢谢,
Nathan

创建一个modelbinder,重写BindModel,检查类型并执行需要执行的操作

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);
    }
}
检查是否匹配泛型基

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

        return false;
    }

由于这个问题在谷歌的搜索结果中排名仍然很高,我想提一提的是,MVC3推出的一个更好的解决方案可能是使用。这使得您不必更换默认绑定器,如果您所做的只是尝试添加绑定特定类型的特殊规则,这使得自定义模型绑定更具可扩展性。我一直在努力寻找如何在mvc 2应用程序中为所有类型设置自定义模型绑定器。这就是解决办法!谢谢!
    private bool HasGenericTypeBase(Type type, Type genericType)
    {
        while (type != typeof(object))
        {
            if (type.IsGenericType && type.GetGenericTypeDefinition() == genericType) return true;
            type = type.BaseType;
        }

        return false;
    }