質問

これは、一般的なタイプのモデルバインダーを作成することは可能ですか?例えば、私はタイプを持っている場合は、

public class MyType<T>

がMyTypeのいずれかのタイプのために働くだろうカスタムモデルバインダーを作成する方法はありますか?

おかげで、 ネイサン

役に立ちましたか?

解決

タイプをチェックし、あなたがする必要が何をすべきか、BindModelをオーバーライドし、modelbinderを作成します。

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

Global.asaxの中でデフォルトにあなたのモデルバインダーを設定します。

protected void Application_Start() {

        // Model Binder for My Type
        ModelBinders.Binders.DefaultBinder = new MyModelBinder();
    }

一般的な塩基を一致させるためのチェック

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

        return false;
    }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top