【发布时间】:2014-01-14 17:09:50
【问题描述】:
我正在尝试实现一个基本的问卷引擎,该引擎使用如下问卷模型:
public class Questionnaire
{
public ICollection<Step> Steps { get; set; }
}
public class Step
{
ICollection<IQuestion> Questions { get; set; }
}
public class TextBoxQuestion : IQuestion
{
public QuestionTypeEnum QuestionType { get; set; }
public string QuestionText { get; set; }
}
public class DropDownQuestion : IQuestion
{
public QuestionTypeEnum QuestionType { get; set; }
public string QuestionText { get; set; }
public IList<string> Options { get; set; }
}
问题编辑器模板:
@model IList<Models.IQuestion>
@for (int i = 0; i < @Model.Count(); i++)
{
@Html.EditorFor(x => x[i], @Model[i].QuestionType.ToString());
}
TextBoxQuestion 编辑器:
public class TextBoxQuestion : IQuestion
{
public QuestionTypeEnum QuestionType { get; set; }
public string QuestionText { get; set; }
}
DropDownQuestion 编辑器:
public class DropDownQuestion : IQuestion
{
public QuestionTypeEnum QuestionType { get; set; }
public string QuestionText { get; set; }
}
大致遵循Jon Egerton's example here 我正在实现 IQuestion 接口的通用 ICollection。 MVC 按其类型解释每个 IQuestion,并相应地呈现 TextBoxQuestion 或 DropDownQuestion 编辑器模板。太好了。
但是,当问卷模型回传到控制器时,IQuestion 集合全部为空。
谁能帮助我就是否有更好的方法或者我是否可以连接一个 DependencyResolver 或其他东西以便 MVC 可以将我的 IQuestion 对象解释为 TextBoxQuestion 和 DropDownQuestion 类型提供建议?
希望这个解释清楚,请随时提出任何问题。
提前谢谢大家
标记
【问题讨论】:
-
您是否按照该文章第 2 部分的说明进行操作?没有它,默认模型绑定器将无法区分这两种具体类型,这意味着它将返回
null。 -
是的,使用自定义 ModelBinder 功能实现了第 2 部分,但我的理解是只解析传递模型的具体类型,我需要解析子 IQuestion 项的具体类型。也许我错过了什么?
标签: c# asp.net asp.net-mvc asp.net-mvc-4 model