How to Insert to Master-detail tables in ASP.NET MVC 5

可紊 提交于 2019-12-06 01:38:17

I think you should use Ajax.

In your view you have the grid section, each time you add a record you have to post the values to the server using Ajax post form:

@using (Ajax.BeginForm("AddDetails", new AjaxOptions { UpdateTargetId = "gridContainerElementId" }))
{
  @Html.HiddenFor(m => m.folio)
  @Html.HiddenFor(m => m.product)
  @Html.TextBox(m => m.price)
  @Html.TextBox(m => m.quantity)
  <input type = "submit" value = "Save"/>
}

Note: put your grid in 'gridContainerElementId' div like:

<div id="gridContainerElementId">
  @Html.Action("DetailsGridPartial", new { OrderId = Model.folio })
</div>

In your controller

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddDetails(OrdersDetail orderDetails)
{
   if (ModelState.IsValid)
   {
      db.OrdersDetail.Add(orderDetails);
      db.SaveChanges();

      return RedirectToAction("DetailsGridPartial", new { OrderId =  orderDetails.folio });
   }
   return View(order);
}

public ActionResult DetailsGridPartial(int OrderId)
{
      var orderDetails = db.OrdersDetail.Where(w => w.folio == OrderId);
      return PartialView(orderDetails);
}

You need to create new view to show the grid:

@model IEnumerable<OrdersDetail>
@Html.YourHelper.Grid(model).Html() @*or however you build the grid*@

In this case you will not need to fill the grid manually by the new record, the grid will be refreshed automatically.

I hope this helps

In your Create Post action method, you need to handle disconnected approach when working with web technologies like MVC, Web API, WCF etc.

Orders should contain list of OrderDetails, when its read in action parameter. Look for if its editing or addition and change Entity state accordingly to Added or Modified.

This usually happens because in web apps EF doesn't deal with entity tracking. Please refer this link EF disconnected apps. Apply the scenario which are similar to your's.

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