MVC3 View With Abstract Property

2020-08-01 05:08发布

问题:

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?

回答1:

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



回答2:

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 .



回答3:

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)
{
    //...
}