I Have a ViewModel that has an interface as a property. When I submit the page, I got the "Cannot create an instance of Interface" error.
The ViewModel is like this:
public class PlanoPagamentoViewModel
{
//some properties
public IPlanoPagamentosParcelas PlanoPagamentosParcelas { get; set; }
}
There're two classes that implement this Interface. The corresponding ViewModels are dinamically loaded with a PartialView, depending on the option that is selected.
public class PlanoPagamentoCartaoViewModel : IPlanoPagamentosParcelas
{
//some properties
}
public class PlanoPagamentoCrediarioViewModel : IPlanoPagamentosParcelas
{
//some properties
}
I did a research and I found that the need of creating a custom model binding, and I did that:
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;
}
}
And add this new custom binding in Global.asax, Application_Start method:
ModelBinders.Binders.Add(typeof(IPlanoPagamentosParcelas), new PlanoPagamentoParcelasBinder());
It works well for PlanoPagamentoCartaoViewModel
, but I would need to have another custom bindings for the PlanoPagamentoCrediarioViewModel
, but I can't just add a new ModelBinders.Binders.Add with the same Key (IPlanoPagamentosParcelas
) because there's already one key with this type.
So, is there any other approach to create a custom model binding for ViewModels that implement the same interface?