Я хочу публиковать дочерние и родительские записи одновременно через EF core, Linq и ASP. NET -CORE- MVC - PullRequest
0 голосов
/ 09 января 2020

Я создаю приложение для чекового принтера. Мне нужно опубликовать квитанцию ​​в БД, чтобы получить ее идентификатор, а затем разместить каждую позицию в отдельной таблице БД с FK (receiveID). Я чувствую, что я очень близок, потому что я могу разместить квитанцию ​​в таблице БД, но позиции не будут публиковаться вообще. PS Я очень новичок в мире кодирования, и C# тем более.

My JS - я использую вызов ajax для публикации каждой позиции в таблице в моем виде:

@model ReceiptPrinterRewrite.Models.ViewModels.ReceiptsVM

@{
    ViewData["Title"] = "General Sales";
}

@section Scripts {

    @*Updating Service Price to Match Service*@
    <script>
        $(document).ready(function () {
            $('#Service').change(function () {
                $('#Price').val($(this).val());
            });
        });
    </script>

    @*Adding Service To Table*@
    <script type="text/javascript">
        function addService() {
            var qty = parseInt($('#Quantity').val()),
                ppu = parseFloat($('#Price').val()),
                total = (qty * ppu).toFixed(2);

            $.ajax({
                type: "Post",
                url: "@(Url.Action("AddLineItem", "Home"))",
                data: {
                    'FkServiceId':parseInt($('#Service').val()),
                    'QTY': qty,
                    'TOTAL': total
                },
                success: function () {

                },
                error: function (result) {
                    alert("Error");
                }
            }).done(function (result) {
                console.log(result);
                var $tbl = $('#LineItems');
                var r = '<tr>' + '<td style="width:140px" name="serviceList">' + result.service + '</td><td style="width:140px" name="quantityList">' + qty + '</td><td style="width:140px" name="priceList">' + $('#Price').val() + '</td><td class="rowTotal" style="width:70px" name="totalList">' + total + '</td><td><input type="button" class="btn btn-danger btn-md" value="X" onClick="removeLineItem(this)" style="width:30px"/></td></tr>';
                $tbl.append(r);
                totalPrice();

            });
        }

    </script>

    @*Running total for receipt*@
    <script>
        function totalPrice() {
            var total = 0.00;
            $(".rowTotal").each(function () {
                total += parseFloat($(this).text());
            });
            $("#ReceiptTotal").val((total).toFixed(2));
        }

    </script>

    @*Delete row*@
    <script type="text/javascript">
        function removeLineItem(btn) {
            var row = btn.parentNode.parentNode;
            row.parentNode.removeChild(row);
            totalPrice();
        }
    </script>

    @*Figuring Change Due*@
    <script type="text/javascript">
        function calcChange() {
            var cashReceived = parseFloat($('#CashReceived').val()),
                amountDue = parseFloat($('#ReceiptTotal').val()),
                changeDue = (cashReceived - amountDue).toFixed(2);
            $('#ChangeDue').val(changeDue);
        }
    </script>

Остальная часть моего View:

<div class="text-center">
    <h1 class="display-4"><strong>General Sales</strong></h1>
</div>

@using (Html.BeginForm("ReceiptsView", "Home", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(false, "", new { @class = "text-danger" })
    @Html.HiddenFor(m => m.Receipt.ReceiptId)



    <div>
        <h3>Employee</h3>
    </div>
    <div class="row">
        <div class="col-sm-2 form-group">
            @Html.TextBoxFor(m => m.Receipt.CurrentEmployee, new { @class = "form-control", placeholder = "Employee Name", id = "EmployeeName" })

            @*@Html.Label("Employee")*@
            @*@Html.DropDownListFor(m => m.CurrentEmployee, (IEnumerable<SelectListItem>)ViewBag.Employees, string.Empty, new { @class = "form-control" })*@
        </div>
    </div>

    <div class="text-center">
        <h3><u>Customer Information</u></h3>
    </div>
    <div class="row">
        <div class="offset-4 col-sm-4 form-group">
            @Html.TextBoxFor(m => m.Receipt.Name, new { @class = "form-control", placeholder = "Customer Name", id = "CustomerName" })
        </div>
    </div>
    <br />
    <div class="text-center">
        <h3><u>Receipt Line Items</u></h3>
    </div>
    <div class="row">
        <div class="offset-3 col-sm-3 form-group">
            @Html.DropDownList("Service", (IEnumerable<SelectListItem>)ViewBag.Service, "Services", new { @class = "form-control", placeholder = "Services", id = "Service" })
        </div>
        <div class="col-sm-1 form-group">
            @Html.TextBoxFor(m => m.LineItem.LineItemQty, new { @class = "form-control", placeholder = "Qty", id = "Quantity" })
        </div>
        <div class="col-sm-1 form-group">
            @Html.TextBox("Price", string.Empty, new { @class = "form-control", placeholder = "Price", id = "Price" })
        </div>
        <div class="col-sm-1 form-group">
            <input type="button" value="Add" class="btn btn-success form-group" onclick="addService()" />
        </div>
    </div>
    <br />
    <div class="row">
        <div class="offset-2 col-md-7">
            <table id="LineItems" class="table table-striped">
                <thead>
                    <tr>
                        <th style="width:140px">
                            @Html.Label("Service")
                        </th>
                        <th style="width:140px">
                            @Html.Label("Quantity")
                        </th>
                        <th style="width:140px">
                            @Html.Label("Price Per Unit")
                        </th>
                        <th style="width:70px">
                            @Html.Label("Total")
                        </th>
                        <th style="width:30px"></th>
                    </tr>
                </thead>
                <tbody>
                    @if (Model.LineItems.Count > 0)
                    {
                        foreach (var item in Model.LineItems)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(m => item.FkServiceId)
                                </td> <td>
                                    @Html.DisplayFor(m => item.LineItemQty)
                                </td> <td>
                                    @Html.DisplayFor(m => item.LineItemPrice)
                                </td>                                
                            </tr>
                        }
                    }
                </tbody>
            </table>
        </div>
    </div>
    <div class="row">
        <div class="offset-7 col-sm-1">
            @Html.TextBoxFor(m => m.Receipt.TotalDue, new { @class = "form-control", placeholder = "Total", id = "ReceiptTotal", @readonly = "readonly" })
        </div>
    </div>
    <br />
    <br />
    <div class="text-center">
        <h3><u>Payment Info</u></h3>
    </div>
    <div class="row">
        <div class="offset-2 col-sm-2">
            @Html.TextBoxFor(m => m.Receipt.CashReceived, new { @class = "form-control", placeholder = "Cash Received", id = "CashReceived", @onChange = "calcChange()" })
        </div>
        <div class="offset-4 col-sm-1">
            @Html.TextBoxFor(m => m.Receipt.ChangeDue, new { @class = "form-control", placeholder = "Change", id = "ChangeDue", @readonly = "readonly" })
        </div>
    </div>
    <br />
    <div class="row">
        <div class="offset-2 col-sm-2">
            @Html.TextBoxFor(m => m.Receipt.CheckReceived, new { @class = "form-control", placeholder = "Check Received", id = "CheckReceived" })
        </div>
        <div class="col-sm-2">
            @Html.TextBoxFor(m => m.Receipt.CheckNumber, new { @class = "form-control", placeholder = "Check #", id = "CheckNumber" })
        </div>
    </div>
    <br />
    <br />
    <br />
    <div class="row">
        <div class="offset-2 col-sm-2 form-group">
            <input type="submit" value="Print Receipt" class="btn btn-success center-block" />
        </div>
    </div>
}

My ViewModel:

using ReceiptPrinterRewrite.Models.DataModels;

namespace ReceiptPrinterRewrite.Models.ViewModels
{
    public class ReceiptsVM
    {
        public Receipt Receipt { get; set; }
        public LineItem LineItem { get; set; }
        public IList<LineItem> LineItems { get; set; }

        public ReceiptsVM()
        {
            Receipt = new Receipt();
            LineItem = new LineItem();
            LineItems = new List<LineItem>();
        }
    }
}

И, наконец, мои действия в моих контроллерах: Сначала добавьте позицию в Просмотрите

 public async Task<ActionResult> AddLineItem(int FkServiceId, int QTY, decimal TOTAL)
        {
            using (var context = new ReceiptPrinter_DevContext())
            {
                if (ModelState.IsValid)
                {
                    LineItem lineitem = new LineItem
                    {
                        FkServiceId = FkServiceId,
                        LineItemQty = QTY,
                        LineItemPrice = TOTAL,                        
                    };

                    //context.LineItems.Add(lineitem);
                    //await context.SaveChangesAsync();
                    var service = await context.Services.Where(a => a.ServiceId == lineitem.FkServiceId).Select(a => a.ServiceDescription).FirstOrDefaultAsync();
                    var result = new {service, lineitem };
                    return Json(result);
                }
                return View("ReceiptsView");
            }
        }

и действие Post, чтобы добавить все в базу данных

    [HttpPost]
    [ValidateAntiForgeryToken]

    public async Task<IActionResult> ReceiptsView(ReceiptsVM receiptsVM )
    {
        using (var context = new ReceiptPrinter_DevContext())
        {
            if (ModelState.IsValid)
            {
                try
                {
                receiptsVM.Receipt.Status = context.CodeTables.Where(a => a.CodeDef == "OK").Select(a => a.CodeTableId).FirstOrDefault();
                context.Receipts.Add(receiptsVM.Receipt);                       
                foreach (LineItem item in receiptsVM.LineItems)
                {
                        LineItem linteitem = new LineItem
                        {
                            FkReceiptId = receiptsVM.Receipt.ReceiptId,
                            LineItemQty = item.LineItemQty,
                            LineItemPrice = item.LineItemPrice,
                            FkServiceId = item.FkServiceId
                        };

                        context.LineItems.Add(item);
                }
                await context.SaveChangesAsync();
                return RedirectToAction("ReceiptsView", "Home");

                }
                catch (DbUpdateConcurrencyException)
                {
                    return NotFound();
                }
            };
            return View(receiptsVM);
        }
    }

Возможно, потому что у меня нет HTML помощников специально для модели Lineitems, она даже не отправляет ничего на контроллере для публикации в БД?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...