2010-04-15 2 views
2

올바른 유형을 만들기 위해 인터페이스에 바인딩해야하는 시나리오가 있습니다. 올바른 콘크리트 유형을 만드는 방법을 알고있는 사용자 정의 모델 바인더가 있습니다. 다를 수 있음).ModelBinders, 복잡한 중첩 유형 및 인터페이스

그러나 생성 된 유형에는 필드가 올바르게 채워지지 않습니다. 여기에 간단한 블로깅이 있습니다.하지만 모델 바인더가 수행해야하는 작업이 필요한 이유는 무엇입니까? 작업하고 속성을 바인딩할까요?

public class ProductModelBinder : DefaultModelBinder 
{ 
    override public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) 
    { 
     if (bindingContext.ModelType == typeof (IProduct)) 
     { 
      var content = GetProduct (bindingContext); 

      return content; 
     } 

     var result = base.BindModel (controllerContext, bindingContext); 

     return result; 
    } 

    IProduct GetProduct (ModelBindingContext bindingContext) 
    { 
     var idProvider = bindingContext.ValueProvider.GetValue ("Id"); 
     var id = (Guid)idProvider.ConvertTo (typeof (Guid)); 

     var repository = RepositoryFactory.GetRepository<IProductRepository>(); 
     var product = repository.Get (id); 

     return product; 
    } 
} 

내 경우에는 모델은 i- 제품 속성을 가진 복합 형이며, 내가 채워 필요가 해당 값의

모델 :.

[ProductBinder] 
public class Edit : IProductModel 
{ 
    public Guid Id { get; set; } 
    public byte[] Version { get; set; } 

    public IProduct Product { get; set; } 
} 

답변

0

ModelBinder를 그렇게 무엇을 재귀 적으로 노력하고 있습니다 당신은 커스텀 모델 바인더를 구현하고, onCreate와 BindModel 메소드를 오버라이드 할 필요가있다.

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) 
{ 
// get actual type of a model you want to create here 
    return Activator.CreateInstance(type); 
} 

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
{ 
    // here our CreateModel method will be called 
    var model = base.BindModel(controllerContext, bindingContext); 
    // we will get actual metadata for type we created in the previous line 
    var metadataForItem = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType()); 
    // and then we need to create another binding context and start model binding once again for created object 
    var newModelBindingContext = new ModelBindingContext 
     { 
      ModelName = bindingContext.ModelName, 
      ModelMetadata = metadataForItem, 
      ModelState = bindingContext.ModelState, 
      PropertyFilter = bindingContext.PropertyFilter, 
      ValueProvider = bindingContext.ValueProvider 
     }; 
     return base.BindModel(controllerContext, newModelBindingContext); 

} 도움이

희망.

관련 문제