ASP.NET MVC3绑定到子类 [英] ASP.NET MVC3 bind to subclass
问题描述
我有型的问题的具有多个子类的父类(如 MultipleChoiceQuestion 的和的 TextQuestion 的)。每个子类中有自己的编辑模板(例如〜/共享/ EditorTemplates / MultipleChoiceQuestion.cshtml 的)。
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 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.
作为测试,我在类型的列表通过的 MultipleChoiceQuestion 的和正常工作:
As a test, I have passed in a list of type MultipleChoiceQuestion and it works fine:
class Questionnaire {
List<MultipleChoiceQuestion> Questions;
}
有什么方法可以让我得到HttpPost行动来回报我与我的表单数据实例化的子类的模式?
Is there any way I can get the HttpPost Action to return my model with the subclasses instantiated with my form data?
感谢
推荐答案
我认为你对DefaultModelBinder的限制运行起来。为了解决这个问题,你需要使用一个客户模型绑定。
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.
这篇关于ASP.NET MVC3绑定到子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!