开发者

How to handle nested models in ASP.NET MVC

I have been looking around for a nice working solution on how to correctly handle model binding with nested attributes. I have one model that has a list of other child models like below:

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

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

In the controller I try to update the data like this:

[HttpPost]
public ActionResult Edit(string organizationIden开发者_StackOverflow中文版tifier, FormCollection values)
{
    var organization = organizationService.GetByIdentifier(organizationIdentifier);

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

    return View("Edit");
}

But the TryUpdateModel always return false and no validation messages are displayed in the UI. The UI is built using the standard MVC helper EditorFor.

What is the best practice of doing this? For a pretty normal scenario there is not that easy to find information.

Thanks!


Now is the ID column what you are querying for with the GetByIdentifier? If so, why are you passing in a string, but have it as an int in the definition?

Also by reading about TryUpdateModel, it sounds like you might want to use UpdateModel instead.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜