I 인터페이스를 속성으로 가진 ViewModel이 있습니다. 페이지를 제출할 때 "인터페이스의 인스턴스를 만들 수 없습니다"오류가 발생합니다.asp.net MVC 모델 바인딩 오류 "인터페이스 인스턴스를 만들 수 없습니다."
뷰 모델은 다음과 같이이다 :
public class PlanoPagamentoViewModel
{
//some properties
public IPlanoPagamentosParcelas PlanoPagamentosParcelas { get; set; }
}
이 인터페이스를 구현하는 두 개의 클래스가있어. 해당하는 ViewModel은 선택한 옵션에 따라 PartialView로 동적으로로드됩니다.
public class PlanoPagamentoCartaoViewModel : IPlanoPagamentosParcelas
{
//some properties
}
public class PlanoPagamentoCrediarioViewModel : IPlanoPagamentosParcelas
{
//some properties
}
나는 연구를했고, 나는 사용자 지정 바인딩 모델을 만들 필요, 나는 그 한 것을 발견 :
public class PlanoPagamentoParcelasBinder : DefaultModelBinder
{
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var type = typeof(PlanoPagamentoCartaoViewModel);
var model = Activator.CreateInstance(type);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
return model;
}
}
을 그리고 Global.asax에, 위해 Application_Start 메서드에서 바인딩이 새 사용자를 추가합니다 :
ModelBinders.Binders.Add(typeof(IPlanoPagamentosParcelas), new PlanoPagamentoParcelasBinder());
그것은 PlanoPagamentoCartaoViewModel
잘 작동하지만, 나는 PlanoPagamentoCrediarioViewModel
에 대해 또 다른 사용자 정의 바인딩이 필요합니다,하지만 난 그냥 함께 새로운 ModelBinders.Binders.Add를 추가 할 수 없습니다 동일한 키 (IPlanoPagamentosParcelas
)가 이미이 유형의 키가 하나 있기 때문입니다.
그래서 동일한 인터페이스를 구현하는 ViewModels에 대한 맞춤 모델 바인딩을 만드는 다른 방법이 있습니까? 위의 코드 var typeValueProvider = bindingContext.ValueProvider.GetValue("Type");
Type
에서
protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
var typeValueProvider = bindingContext.ValueProvider.GetValue("Type");
var type = (int)typeValueProvider.ConvertTo(typeof(int));
Type instanceType = null;
switch (type)
{
case 1:
instanceType = typeof(PlanoPagamentoCartaoViewModel);
break;
case 2:
instanceType = typeof(PlanoPagamentoCrediarioViewModel);
break;
}
if (!typeof(IPlanoPagamentosParcelas).IsAssignableFrom(instanceType))
{
throw new InvalidOperationException("Bad Type");
}
var model = Activator.CreateInstance(instanceType);
bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, instanceType);
return model;
}
는 인스턴스화 콘크리트하는 클래스를 결정하는 것이 될 것이다 :
typeof (IPlanoPagamentosParcelas)를 typeof (PlanoPagamentoParcelasBinder) 또는 typeof (DefaultModelBinder)로 변경하십시오. –
@viveknuna 동일한 오류가 발생했습니다. 두 개의 ViewModels에 IPlanoPagamentosParcelas를 추가해야하지만, 사전이므로 – Maturano