开发者

How to get TryUpdateModel to update a child object also in Asp.net MVC2

I have an object (Object1), which contains a child object (Child). Thus, you would access the child by Object1.Child. In my ASP.NET MVC2 project, I a receiving the POST reply to the create method. The FormCollection contains properties for both the Object1 and Child objects. I cannot seem to get the child object to be updated with the "TryUpdateModel" function.

[H开发者_JAVA技巧ttpPost]
    public ActionResult Create(FormCollection collection)
    {
        Object1 obj = new Object1();
        obj.Child = new Child();
        if (TryUpdateModel<Object1>(obj, "Object1", new[] { "ObjectName", "Child.ChildName" }))
        {
            // At this point, "ObjectName" is filled in, but "Child.ChildName" is not.
            context.Object1s.AddObject(obj);
            context.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(new Object1_ViewModel(obj));
    }

Any help is appreciated.


If you have a strongly typed view you could try to do something like

public ActionResult Create(Object1 obj)

I am not positive if the default model binder will carry any child objects through. If that doesn't work you may have to roll your own Model Binder. See the following links on how you can write one:

http://www.codethinked.com/post/2009/01/08/ASPNET-MVC-Think-Before-You-Bind.aspx

http://www.codethinked.com/post/2010/04/12/Easy-And-Safe-Model-Binding-In-ASPNET-MVC.aspx

ASP.NET MVC2 - Custom Model Binder Examples

http://codeisvalue.wordpress.com/2010/02/10/customizing-model-binder-in-asp-net-mvc/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜