【问题标题】:How to handle nested models in ASP.NET MVC如何在 ASP.NET MVC 中处理嵌套模型
【发布时间】:2011-03-09 01:16:20
【问题描述】:

我一直在寻找关于如何正确处理具有嵌套属性的模型绑定的良好工作解决方案。我有一个模型,其中包含其他子模型的列表,如下所示:

public class Organization : IEntity
{
    [ScaffoldColumn(false)]
    public int ID
    {
        get; 
        set;
    }

    [LocalizedDisplayName("Goals")]
    public virtual ICollection<OrganizationGoal> Goals
    {
        get;
        set;
    }
}

在控制器中,我尝试像这样更新数据:

[HttpPost]
public ActionResult Edit(string organizationIdentifier, FormCollection values)
{
    var organization = organizationService.GetByIdentifier(organizationIdentifier);

    if (TryUpdateModel(organization))
    {
       organizationService.Save(organization);
       return RedirectToAction("Edit");
    }

    return View("Edit");
}

但 TryUpdateModel 始终返回 false,并且 UI 中不会显示任何验证消息。 UI 是使用标准 MVC 帮助器 EditorFor 构建的。

这样做的最佳做法是什么?对于一个非常正常的情况,没有那么容易找到信息。

谢谢!

【问题讨论】:

  • Kristoffer,您能否提供一些有关通过 FormCollection 发布哪些键值对的详细信息?

标签: asp.net-mvc-2 model-binding


【解决方案1】:

现在是您使用 GetByIdentifier 查询的 ID 列吗?如果是这样,你为什么要传入一个字符串,但在定义中将它作为一个 int ?

另外,通过阅读 TryUpdateModel,听起来您可能想改用 UpdateModel。

http://msdn.microsoft.com/en-us/library/dd460189.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 2011-09-26
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多