【问题标题】:ASP.NET MVC: model binding complex typeASP.NET MVC:模型绑定复杂类型
【发布时间】:2011-06-22 13:31:35
【问题描述】:

我在绑定到对象列表时遇到问题。 使用 Mvc3.1 和工具更新。

当绑定到 Form 类时,HttpPost 函数接收到正确的模型。 当绑定到 FormViewModel 时,HttpPost 函数接收一个空模型。

绑定包含其他模型的模型有什么限制吗?

public class FormViewModel
{
    public Form Form { get; set; }
}

public class Form
{
    public List<Section> Sections { get; set; }
}

public class Section
{
    public List<Question> Questions { get; set; }
}

public class Question
{
    public int Id { get; set; }
    public string Description { get; set; }
}

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    输入元素的名称属性是活页夹用作发挥其魔力的上下文。我的猜测是您的视图包含以下内容:

    @model Form
    @Html.EditorFor(m => m.Sections)
    

    您的 post 方法如下所示:

    [HttpPost]
    public ActionResult Function(FormViewModel formViewModel)
    {
        // ...
    }
    

    如果您将视图更改为:

    @model FormViewModel
    @Html.EditorFor(m => m.Form.Sections)
    

    而您的 get 操作返回 FormViewModel 的实例,它可能会正常工作。助手将使用 lambda 表达式的主体来创建输入元素的名称。在这种情况下,它将创建类似Form.Sections[0].Field 的内容。然后,模型绑定器能够获取 Form.Sections[] 并正确初始化 FormViewModel。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-26
      • 2023-03-18
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      相关资源
      最近更新 更多