How to model bind a class that implements an interface?

后端 未结 1 581
终归单人心
终归单人心 2021-01-03 07:07

The model binding worked fine until i implemented interfaces on top of the following classes:

public class QuestionAnswer : IQuestionAnswer
    {

        pu         


        
相关标签:
1条回答
  • 2021-01-03 07:09

    what am i doing wrong?

    You cannot expect the model binder to know that when it encounters the IQuestionAnswer interface on your SurveyAnswer view model it should use the QuestionAnswer type. It's nice that you have declared this implementation of the interface but the model binder has no clue about it.

    So you will have to write a custom model binder for the IQuestionAnswer interface (same for the IHiddenAnswer interface) and indicate which implementation do you want to be used:

    public class QuestionAnswerModelBinder : DefaultModelBinder
    {
        protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
        {
            var type = typeof(QuestionAnswer);
            var model = Activator.CreateInstance(type);
            bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, type);
            return model;
        }
    }
    

    which will be registered in your Application_Start:

    ModelBinders.Binders.Add(typeof(IQuestionAnswer), new QuestionAnswerModelBinder());
    
    0 讨论(0)
提交回复
热议问题