8

I have a superclass of type Question which has multiple subclasses (e.g. MultipleChoiceQuestion and TextQuestion). Each of the subclasses have their 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 really contain instances of the subclasses:

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

I then pass the questionnaire to the View, where I call:

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

The view successfully renders the correct editor templates for the specific subclass Question models.

The problem is that when the form is submitted, my Questionnaire model (which contains a list of type Question) contains only instances of Question and not the instances of the subclasses. Furthermore the instances of Question properties are all null.

As a test, I have passed in a list of type MultipleChoiceQuestion and it works fine:

class Questionnaire {
    List<MultipleChoiceQuestion> Questions;
}

Is there any way I can get the HttpPost Action to return my model with the subclasses instantiated with my form data?

Thanks

user853894
  • 83
  • 1
  • 4
  • This should really be submitted to the ASP.NET MVC team as a feature suggestion. I don't believe it would be too hard for them to check `GetType()` of the current model object and get the template based on that - and doing so would probably solve the problem =) – Tomas Aschan Jul 20 '11 at 12:53
  • Tomas, I don't think that's the problem. There is a type specified for the model and the binder is building an instance of that type from the data in the form. Rather, the binder needs to been able to identify from the form what subclass is required; hence the need for a custom binder. – Steve Morgan Jul 20 '11 at 12:57
  • Can you post the MultipleChoiceQuestion.cshtml or at least part of it? I know I had issues with check boxes not posting back the right values before. Could that be part of the issue? – Ed Charbeneau Jul 20 '11 at 13:00

1 Answers1

2

I think you're running up against a limitation of the DefaultModelBinder. To solve this problem, you need to use a customer model binder.

You might find this post a useful guide; it talks about this specific problem.

Steve Morgan
  • 12,978
  • 2
  • 40
  • 49
  • [This post](http://lostechies.com/jimmybogard/2011/07/07/intelligent-model-binding-with-model-binder-providers/) is an updated version of the post linked to above. While the post did not solve my problem, it did lead me to a workaround. By passing the type of the subclass down to the view I was able to retrieve it in my custom model builder and using reflection create an instance of the subclass. – user853894 Jul 21 '11 at 16:32