MVC2 RTM - model binding complex objects using Entity Framework

百般思念 提交于 2019-12-02 04:16:07

Thanks for this question, even though it wasn't answered it gave me my answer. The best thing I can find to do is this (using your example):

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
        {
            EFEntities ef = new EFEntities();
            ParentObject parent = ef.ParentObjects.SingleOrDefault(p => p.ID == id);

            if (ModelState.IsValid)
            {
                int i = 0;
                foreach (child in parent.ChildObjects)
                {
                    //this works fine
                    TryUpdateModel(child, "ChildObjects[" + i + "]"); 
                    i++;
                }

                //exclude the collections and it won't blow up...
                if (TryUpdateModel(parent, "Parent", null, new string[] {"ChildObjects"})) 
                {                    
                    ef.SaveChanges();
                    return RedirectToAction("Details", new { id = parent.ID });
                }
            }
            return View(parent);
        }

Ultimately I found a more elegant solution, but never came back to post it. Here it is - sorry for the delay:

if (ModelState.IsValid)
        {
            if (TryUpdateModel(parent, new[] "prop1", "prop2", "prop3" })) //specify parent-only properties to include
            {
                if (TryUpdateModel(parent.ChildObjects, "ChildObjects"))
                {
                    _ef.SaveChanges();
                    return RedirectToAction("Details", new { id = parent.ID })                    }
            }
        }
        return View(parent);

I'm converting this code from a real life app, so my apologies for any typos.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!