ASP.NET MVC3 bind to subclass

本小妞迷上赌 提交于 2020-01-01 04:55:12

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/6762168/asp-net-mvc3-bind-to-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!