문제

일반 유형의 모델 바인더를 만들 수 있습니까? 예를 들어, 유형이있는 경우

public class MyType<T>

모든 유형의 myType에 맞는 사용자 정의 모델 바인더를 만들 수있는 방법이 있습니까?

고마워, 나단

도움이 되었습니까?

해결책

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

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