views:

69

answers:

1

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.

[HttpPost]
    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.

+1  A: 

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

http://stackoverflow.com/questions/2343913/asp-net-mvc2-custom-model-binder-examples

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

Scott Lance