如何在ASP.NET MVC 5中插入到主从表 [英] How to Insert to Master-detail tables in ASP.NET MVC 5

查看:224
本文介绍了如何在ASP.NET MVC 5中插入到主从表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库中有 Orders 表和 OrderDetails 表.使用Entity Framework 6,我已经获得了一个模型,因此可以从中生成类.我还从Orders表生成了控制器和视图.

I have Orders table and OrderDetails table in DB. With Entity Framework 6 I have obtained a model so I have classes generated from it. I also generated controllers and views from the Orders table.

Orders
folio (PK)
date
customer (FK)

OrdersDetail
folio (FK) -- to the Orders table
product (FK)
price
quantity 

生成的创建帖子"操作如下:

The generated Create Post action is the following:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "folio,date,customer")] Orders order)
        {

            if (ModelState.IsValid)
            {
                db.Orders.Add(order);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.cliente = new SelectList(db.CATCTES, "COD_CTE", "NOM_CTE", order.cliente);

            return View(order);
        }

没关系,但是我也需要插入其他实体/表! 我已经更改了Create.cshtml表单,其中包含Orders表所需的字段,并为OrdersDetail包含了某种网格.每行都是OrdersDetail表的新条目.

That's okay, but I would need to Insert to the other entity/table too! I already changed the Create.cshtml form, with the fields required for Orders table and including some kind of grid for OrdersDetail. Each row is a new entry for OrdersDetail table.

问题在于,我不知道如何正确地保存到订单"控制器中的创建"操作中的另一张表.如果这不是正确的方法,请告诉我您的评论.

The problem, is I don't know how to properly save to the other table in the Create action at Orders controller. If this is not the right approach, tell me your comments.

另一个问题是关于POST,我应该如何命名输入以进行正确分组并在控制器上使用提交的值?当我单击表单上的"+"按钮时,此脚本将生成每一行:

Another concern is about POSTing, How should I name the inputs to be properly grouped and use submitted values at controller? Each row is generated by this script when I click a "+" button on the form:

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script>
        function add_row() {
            var detalle = $('#detalle');
            var newRow = '<tr>' + 
                            '<td data-title="Product">' +
                              '<div class="input-group">' +
                                '<span class="input-group-addon"></span>' +
                                  '<input class="form-control" type="number" aria-label="Product" name="detail_array[].product" step="0.001" min="0.000" onchange="cambiar_importe(this)" required="true">' +
                              '</div>' +
                            '</td>' +
                            '<td data-title="Price" >' +
                              '<div class="input-group">' +
                                '<span class="input-group-addon">$</span>' +
                                  '<input type="number" class="form-control" aria-label="Price" name="detail_array[].price" onchange="cambiar_importe(this)" step="0.001" min="0.000" required="true">' +
                              '</div>' +
                            '</td>' +
                            '<td data-title="Quantity">' +
                              '<div class="input-group">' +
                                '<span class="input-group-addon">$</span>' +
                                  '<input type="text" class="importe form-control" aria-label="Quantity" name="detail_array[].quantity" step="0.001" min="0.000" readonly="true" >' +
                              '</div>' +
                            '</td>' +
                            '<td data-title=""><button type="button" class="btn btn-danger btn-sm" onclick="borrar_renglon(this)">Cancelar</button></td>' +
                          '</tr>';

            detalle.append(newRow);
        }

    </script>
}

推荐答案

我认为您应该使用Ajax.

I think you should use Ajax.

在您的视图中,您拥有网格部分,每次添加一条记录时,您都必须使用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"/>
}

注意:将网格放在'gridContainerElementId'div中,如下所示:

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

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

在您的控制器中

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

我希望这对您有帮助

这篇关于如何在ASP.NET MVC 5中插入到主从表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆