我有一个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