2010-06-28 40 views
4

我一直在尋找一個很好的工作解決方案,以便如何正確處理與嵌套屬性的模型綁定。我有了像下面其他子模型的列表中選擇一個模式:如何在ASP.NET MVC中處理嵌套模型

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構建的。

這樣做的最佳做法是什麼?對於一個非常正常的情況,不容易找到信息。

謝謝!

+0

的Kristoffer,您可以包括一些細節哪些鍵值對正在通過的FormCollection貼? – 2011-01-17 22:50:55

回答

0

現在ID列是你正在查詢的GetByIdentifier?如果是這樣,爲什麼你傳遞一個字符串,但它在定義中作爲int?

另外通過閱讀有關TryUpdateModel,它聽起來像你可能想要使用UpdateModel來代替。

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