1

Consider the following.

Models

public class DemographicsModel
{
    public List<QuestionModel> Questions { get; set; }
}

//Does not work at all if this class is abstract.
public /*abstract*/ class QuestionModel
{
    //...
}

public class ChooseOneQuestionModel : QuestionModel
{
    //...
}

public class ChooseManyQuestionModel : QuestionModel
{
    //...
}

public class RichTextQuestionModel : QuestionModel
{
    //...
}

public class TextQuestionModel : QuestionModel
{
    //...
}

Controller

[HttpPost]
public ActionResult Demographics(DemographicsModel model)
{
    //...
}

My view would have a DemographicsModel with numerous question of all the varying types as shown above. After the form is completed and POSTed back to the server, the Questions property of the Demographics model is re-populated with the correct number of questions but they are all of type QuestionModel instead of the concrete type.

How do I make this thing understand what type to instantiate?

Josh M.
  • 26,437
  • 24
  • 119
  • 200

3 Answers3

3

Frazell's answer would have worked if my root model was the one that was abstract. However, that's not the case for me so what ended up working was this: http://mvccontrib.codeplex.com/wikipage?title=DerivedTypeModelBinder&referringTitle=Documentation

Josh M.
  • 26,437
  • 24
  • 119
  • 200
  • I've posted an answer to a similar question here: http://stackoverflow.com/questions/9417888/mvc-3-model-binding-a-sub-type-abstract-class-or-interface/ – Marcel de Castilho Mar 06 '12 at 17:41
1

ASP.NET MVC's built in Model Binding doesn't support Abstract classes. You can roll your own to handle the Abstract class though see ASP.NET MVC 2 - Binding To Abstract Model .

Community
  • 1
  • 1
Frazell Thomas
  • 6,031
  • 1
  • 20
  • 21
0

I'm going to jump in here, even though it seems you've already solved it.

But would

public class DemographicsModel<T> Where T : QuestionModel
{
    public List<T> Questions { get; set; }
}

Work?

[HttpPost]
public ActionResult Demographics(DemographicsModel<ChooseOneQuestionModel> model)
{
    //...
}
Daryl Teo
  • 5,394
  • 1
  • 31
  • 37
  • Not in my case because the concrete `QuestionModel` classes can be commingled in the `List`. Thanks. – Josh M. Sep 22 '11 at 01:50