ASP.NET MVC3 Binds to a Subclass

I have a superclass of type Question, which has several subclasses (e.g. MultipleChoiceQuestion and TextQuestion). Each subclass has its own editor templates (e.g. ~ / Shared / EditorTemplates / MultipleChoiceQuestion.cshtml).

What I would like to do is create a list of Question objects:

class Questionnaire { List<Question> Questions; } 

which will actually contain instances of subclasses:

 Questions.Add(new MultipleChoiceQuestion()); Questions.Add(new TextQuestion()); 

Then I pass the questionnaire to the view, where I call:

 @Html.EditorFor(m => m.Questions) 

The view successfully displays the correct editor templates for certain models of subclass models.

The problem is that when I submit the form, my questionnaire model (which contains a list of type Question) contains only instances of the Question, not instances of subclasses. In addition, Question property instances are null.

As a test, I went to a list of type MultipleChoiceQuestion, and it works fine:

 class Questionnaire { List<MultipleChoiceQuestion> Questions; } 

Is there any way I can force the HttpPost action to return my model with subclasses created using my form data?

thanks

+8
c # data-binding asp.net-mvc-3 razor
source share
1 answer

I think you are faced with the restriction of DefaultModelBinder. To solve this problem, you need to use a connecting device for the model.

You can find this post a useful guide; he talks about this particular problem.

+2
source share

All Articles