2012-03-28 7 views
24

MVC 4에서 사용자 정의 IModelBinder을 만드는 방법을 알아야하며 변경되었습니다.MVC 4 ModelBinder

구현되어야하는 새로운 방법은 :

bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext); 

답변

27

2 개 IModelBinder 인터페이스 있습니다

이전 버전과 동일하고 변경되지 않은
  1. System.Web.Mvc.IModelBinder
  2. 웹 API 및 ApiController에서 사용하는 System.Web.Http.ModelBinding.IModelBinder입니다. 따라서 기본적으로이 방법에서는 actionContext.ActionArguments을 해당 값으로 설정해야합니다. 더 이상 모델 인스턴스를 반환하지 않습니다.
+0

Yesss, Thanks Darin. –

+3

맞춤형 모델 바인더를 등록해야하는 경우도 있습니다. ASP.Net 웹 API에는 MVC3과 같은 방법이 없습니다. [이 게시물] (http://forums.asp.net/t/1773706.aspx/1)에서 MVC4 베타에서 수행하는 방법을 확인하십시오. 대답의 밑바닥은 알아 내기가 어렵지만,'GlobalConfiguration.Configuration.ServiceResolver.GetServices ... '를 사용하여'global.asax.cs'에 설정하십시오. – Steve

24

This link은 완전한 대답을 제공합니다. 여기에 참조 용으로 추가하겠습니다. 신용 asp.net 포럼 dravva에 간다.

먼저 IModelBinder에서 파생 된 클래스를 만듭니다. Darin이 말했듯이 익숙한 MVC가 아닌 System.Web.Http.ModelBinding 네임 스페이스를 사용해야합니다.

다음으로 새 바인더 및 나중에 추가 할 수있는 다른 바인더의 팩터로 작동하는 공급자를 제공하십시오.

public class CustomModelBinderProvider : ModelBinderProvider 
{ 
    CustomModelBinder cmb = new CustomModelBinder(); 
    public CustomModelBinderProvider() 
    { 
     //Console.WriteLine("In CustomModelBinderProvider ctr"); 
    } 

    public override IModelBinder GetBinder(
     HttpActionContext actionContext, 
     ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType == typeof(User)) 
     { 
      return cmb; 
     } 

     return null; 
    } 
} 

마지막으로 Global.asax.cs에 다음을 포함하십시오 (예 : Application_Start).

var configuration = GlobalConfiguration.Configuration; 

IEnumerable<object> modelBinderProviderServices = configuration.ServiceResolver.GetServices(typeof(ModelBinderProvider)); 
List<Object> services = new List<object>(modelBinderProviderServices); 
services.Add(new CustomModelBinderProvider()); 
configuration.ServiceResolver.SetServices(typeof(ModelBinderProvider), services.ToArray()); 

이제 새로운 유형을 조치 방법에 대한 매개 변수로 삭제할 수 있습니다.

public HttpResponseMessage<Contact> Get([ModelBinder(typeof(CustomModelBinderProvider))] User user) 

또는

public HttpResponseMessage<Contact> Get(User user) 
+0

명시 적으로 [ModelBinder (typeof (CustomModelBinderProvider))]를 사용하면 ModelBinderProvider가 필요하지 않습니다. –

3

토드의 ​​게시물에 대한 사후 RC 업데이트 :

이 모델 바인더 공급자가 간단 해졌습니다 추가 :

var configuration = GlobalConfiguration.Configuration; 

configuration.Services.Add(typeof(ModelBinderProvider), new YourModelBinderProvider()); 
+1

이것은 나를 위해 일했습니다. 이 작업을 전 세계적으로 수행 할 수있는 방법이 있습니까? 즉, 기본 모델 바인더를 설정 하시겠습니까? –

8

이보다 간단한 방법은 추가 ModelBinderProvider가없는 모델 바인더는 다음과 같습니다.

GlobalConfiguration.Configuration.BindParameter(typeof(User), new CustomModelBinder()); 
+0

이것은 완벽하게 작동했습니다! 어떤 이유로 든이 페이지의 다른 예제를 MVC4에서 사용할 수 없습니다. ModelBinderProvider의 인터페이스가 변경된 것 같습니다. 그러나 ModelBinderProvider를 제거하고이 코드를 Application_Start에 추가하면 멋졌습니다! –