【问题标题】:MVC4 Generic Collection model issue on POSTPOST 上的 MVC4 通用集合模型问题
【发布时间】: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


【解决方案1】:

如果有人试图实现同样的目标,请找到解决方案。

这篇文章on MSDN Magazine 非常有用。

它解释了一些我不理解的关键概念,例如模型绑定是递归的,因此处理会遍历整个对象图并为每个类型应用模型绑定器。

通用抽象模型绑定器的工作是我与自定义 AbstractModelBinderProvider 一起使用的解决方案。

希望这对某人有所帮助

标记

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2017-07-13
    • 1970-01-01
    • 2021-04-27
    相关资源
    最近更新 更多