Iインターフェイスをプロパティとして持つViewModelがあります。私がページを提出すると、「インターフェイスのインスタンスを作成できません」というエラーが表示されます。asp.net MVCモデルバインディングエラー "インターフェイスのインスタンスを作成できません"
ViewModelには、このようなものです:
public class PlanoPagamentoViewModel
{
//some properties
public IPlanoPagamentosParcelas PlanoPagamentosParcelas { get; set; }
}
このインタフェースを実装する2つのクラスがあります。 対応する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
)にはこのタイプのキーがすでに1つあります。
したがって、同じインタフェースを実装するViewModelsのカスタムモデルバインディングを作成する方法はありますか?
typeof(IPlanoPagamentosParcelas)からtypeof(PlanoPagamentoParcelasBinder)またはtypeof(DefaultModelBinder)への変更 –
@viveknuna同じエラーが発生しました。 2つのViewModelのIPlanoPagamentosParcelasを追加する必要がありますが、それは辞書であるため、 – Maturano