簡體   English   中英

用於泛型類型的ASP.NET MVC模型綁定器

[英]ASP.NET MVC Model Binder for Generic Type

是否可以為泛型類型創建模型綁定器? 例如,如果我有一個類型

public class MyType<T>

有沒有辦法創建一個適用於任何類型的MyType的自定義模型綁定器?

謝謝,內森

創建一個模型綁定器,覆蓋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);
    }
}

將模型綁定器設置為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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM