从字符串添加项目以插入数据库表

时间:2018-12-24 03:19:17

标签: javascript c#

我正在尝试从字符串中添加一项以与其他信息一起插入表中。我已经按照购物车指南进行操作,需要将总费用添加到记录中。我在数组中有项目,并添加了我认为是我需要的项目。我遇到的一个问题是在项目的控制器端实现它。以下是我的代码,我不确定100%添加的总价格是否正确。这应该是十进制形式。感谢您的帮助。

购物车CSHTML页面。这不只是整个页面的相关部分。

               using (Html.BeginForm("AddOrder", "Parts", new { id = "f" }))
               {
                  <table id="tableOrder" class="table table-hover">
                    <tr>
                        <th>Part Number</th>
                        <th>Unit Price</th>
                        <th>Qty Selected</th>
                        <th>Description</th>
                        <th>Total Price</th>
                    </tr>
                    @foreach (var parts in Model)
                    {
                        <tr>
                            <td>@parts.Material</td>
                            <td>@string.Format("{0:C2}", parts.SellingPrice)</td>
                            <td>@parts.QtySelected</td>
                            <td>@parts.Description</td>
                            <td>@string.Format("{0:C2}", (parts.SellingPrice * parts.QtySelected))</td>
                        </tr>
                        totalOrder += (parts.QtySelected * parts.SellingPrice);

                        @Html.HiddenFor(p => parts.Material)
                        @Html.HiddenFor(p => parts.QtySelected)

                    }
                </table>
                <!-- TOTAL PRICE-->
                <h4 style="margin-left: 66%;">Total : <span class="label label-info">@string.Format("{0:C2}", totalOrder)</span></h4>
                     @Html.HiddenFor(p => totalOrder)
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" id="close" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="SaveOrder" data-toggle="modal" data-target="#additionalInfo">Save Order</button>
                </div> <!-- MODAL FOOTER-->
    }

Java脚本部分。

        $("#SaveOrder").click(function () {

        var $form = $(this).closest('form');
        var dataPart = $form.serializeArray();

        console.log(dataPart);

        var arrIdPart = [];
        var arrQtyPart = [];
        var totalPrice = [];

        for (i = 0; i < dataPart.length; i++)
        {
            if (dataPart[i].name == 'parts.Material')
            {
                arrIdPart.push(dataPart[i].value);
            }
            else if (dataPart[i].name == 'parts.QtySelected')
            {
                arrQtyPart.push(dataPart[i].value);

            }
            else if (dataPart[i].name == 'totalOrder')
            {
                totalPrice.push(dataPart[i].value);
            }
        }

        $.ajax({
            type: 'POST',
            url: '@Url.Action("AddOrder", "Parts")',
            data: { arrIdPart, arrQtyPart },
            success: function (response) {
                if(response.data == true)
                {
                    alert("Order has saved successfully ");
                }
                else
                {
                    alert("Order did not save successfully ! ");
                }

            },
            error: function (error) {
                alert("Order did not collect data successfully ! ");
            }
        });
    });

这是控制器动作。我已将所有与总价格有关的部分添加到其中。问题是如何在添加到客户的记录中实现它。

     [HttpPost]
    public ActionResult AddOrder(string[] arrIdPart, int[] arrQtyPart, decimal[] totalPrice)
    {
        int countPart = arrIdPart.Length;
        int CompanyId = (int)Session["CompanyId"];
        bool statusTran = false;

编辑-添加

        decimal totPrice = totalPrice.Length;

        CustomerEntities _context = new CustomerEntities();

        using (DbContextTransaction dbTran = _context.Database.BeginTransaction())
        {
            try
            {
                CompanyNames customer = _context.CompanyNames.Find(CompanyId);

                if (customer != null)
                {

编辑-更改了

                    customer.Ordered.Add(new Orders { OrderDate = DateTime.Now, TotalPrice = totPrice });

                }

                Orders orderSelected = customer.Ordered.LastOrDefault();

                if (orderSelected != null)
                {
                    for (int i = 0; i < countPart; i++)
                    {
                        Parts selectedPart = _context.Parts.Find(arrIdPart[i]);
                        orderSelected.OrderDetail.Add(new OrderDetails { Parts = selectedPart, Quantity = arrQtyPart[i] });
                    }
                }

                //Save Changes
                int countResult = _context.SaveChanges();

                //Commit Transaction
                dbTran.Commit();

                if (countPart > 0)
                {
                    statusTran = true;
                    partsList.Clear();
                }


            }
            catch (Exception)
            {
                dbTran.Rollback();
            }
        }


        return Json(new { data = statusTran }, JsonRequestBehavior.AllowGet);
    }

}

但是我在脚本中没有得到totalOrder的任何信息。说它为空。但是在我的“ console.log(dataPart);”中在控制台中,它的名称为totalOrder。

1 个答案:

答案 0 :(得分:0)

不是说这是最终答案,但我不能在注释中加上多行代码。

我想指出的是,您没有将计算出的总价发布到服务器上:

        type: 'POST',
        url: '@Url.Action("AddOrder", "Parts")',
        data: { arrIdPart, arrQtyPart }, //look, no totalprice data? You did all those efforts to calc it and then did nothing with it?
        success: function (response) {
            if(response.data == true)
出于一致性考虑,

总价格可能应该称为arrSubtotalPart。

警告:服务器接收物品和数量,应该从中计算出价格,而不是让最终用户通过操纵JavaScript来指示他想为订单支付多少费用