1

我正在努力解决同时创建父对象和子对象的情况。理想情况下,我想在单个表单中创建父节点,并从该表单中添加表格格式的子节点。当我尝试将子节点添加到父对象的集合中时出现问题,而父对象本身尚未创建。

简化后,程序代码如下所示:

父创建表单 HTML5 Razor:

@using (Html.BeginForm))
{
   <table>
       <tr>
           <th>Child header</th>
       </tr>
       @if (ViewBag.Children_list != null)
       {
           foreach (var item in (ViewBag.Children_list as List<Child>))
           {
           <tr>
               <td>@item.Child_name</td>
               <td>@Html.ActionLink("Delete child" , "DeleteParentSection", "Partial", new { ChildType = Defs.Child, ChildID = item.ID}, null)</td>
           </tr>
           }
       } 
   </table>
   <p>
      @Html.ActionLink("Add Child", "CreateParentSection", "Partial", new { ParentID = Model.ParentID, ChildType = Defs.Child}, null)
   </p>
}

两个引用的控制器如下所示:

 public ActionResult CreateParentSection(int ParentID , int ChildType)
 {
     Parent parent = db.Parents.Find(ParentID);

     switch (ChildType)
     {
         case Defs.Child:
             Child child= new Child();
             Parent.Children.Add(child);
             break;
         case Defs.AnotherChild:
             (...)
     }

     db.SaveChanges();
     return Redirect(Request.UrlReferrer.ToString());
 }

和:

public ActionResult DeleteParentSection(int ChildType, int ChildID)
{
    switch (ChildType)
    {
        case Defs.Child:
            Child child = db.AllChildren.Find(ChildID);
            db.AllChildren.Remove(child);
            break;
        case Defs.AnotherChild:
            (...)
    }

    db.SaveChanges();
    return Redirect(Request.UrlReferrer.ToString());
}

当程序尝试在CreateParentSection操作中从其 ParentID 中找到活动的 Parent 对象时,找不到父对象,因为父对象仍未保存。

我相信在我允许用户添加子对象之前保存父对象是可能的,但在我看来这似乎是一个不需要的解决方案,因为我喜欢保持干净的设计模式,它会破坏输入代码的混乱验证。

有谁知道一种干净的方法来解决这种问题?

4

0 回答 0