MVC2 RTM - model binding complex objects using Entity Framework

前端 未结 2 1425
情深已故
情深已故 2021-01-25 11:36

I am new to MVC, and am really struggling with what I seems like it should be a very common scenario. I\'m using MVC2 RTM, and the Entity Framework for my model objects.

<
2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-25 11:46

    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);
            }
    

提交回复
热议问题