我有一個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
),因爲此類型已有一個密鑰。
那麼,是否有任何其他方法來創建實現相同接口的ViewModel的自定義模型綁定?
將typeof(IPlanoPagamentosParcelas)更改爲typeof(PlanoPagamentoParcelasBinder)或typeof(DefaultModelBinder) –
@viveknuna我得到了同樣的錯誤。 我需要添加IPlanoPagamentosParcelas兩個的ViewModels,但因爲它是一本字典 – Maturano