更新订单数量的按钮未按预期工作

Button to Update the Order Quantity is not working as expected

我想要一个按钮,允许用户更新他们订购的商品的数量。当用户尝试更新超过可用数量的数量时,我什么都不用做,并显示一条错误消息,指出输入的数量超过可用数量,不应更新数据库中的任何内容

景色

      <form asp-action="EditItem">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
         ..............
                       <!--<input type="text" class="text-danger float-right" style="border:none;font-size: smaller" id="@("errorMessage")"" readonly /> -->
                <div class="form-group">
                <label asp-for="OrderQuantity" class="control-label"></label>
                <input asp-for="OrderQuantity" id="txt" class="form-control" />
                <span asp-validation-for="OrderQuantity" class="text-danger"></span>
            </div>
            <input type="hidden" id="orderId" name="orderId" value="@Model.OrderId" />
            <input type="hidden" id="inventoryorderId" name="inventoryorderId" value="@Model.InventoryOrderId" />
            <input type="hidden" id="inventoryId" name="inventoryId" value="@Model.InventoryId" />
            <button id="button">Update</button>
        </form>
       </div>
     </div>

@section Scripts {
<script type="text/javascript">
    $("#button").click(function () {
        var orderedQuantity = $("#txt").val();
        var orderId = $("#orderId").val();
        var inventoryorderId = $("#inventoryorderId").val();
        var inventoryId = $("#inventoryId").val();

        var data = {
            orderId: orderId,
            inventoryorderId: inventoryorderId,
            inventoryId: inventoryId,
            orderedQuantity: orderedQuantity
        };

        $.ajax({
            type: 'POST',
            url: '@Url.Action("EditItem", "Orders")',
            data: data,
            dataType: "json",
            success: function (result) {
                if (result !== "") {
                    if (result.available == "NotAvailable")
                        $("#errorMessage").val("Enter a valid Quantity");
                }
                else if (result == "")  {
                    var url = '@Url.Action("Index", "Orders")';
                    window.location.href = url + "?custEmail=xy@rrr.org";
                }
            },
            error: function (error) {
                alert(error);
            }
        });
    });
    </script>
    }

控制器操作

    public async Task<JsonResult> EditItem(int? orderId, int? inventoryorderId, int? inventoryId, int? orderedQuantity)
    {
        var inventoryOrder = await _context.InventoryOrders
            .FirstOrDefaultAsync(io => io.InventoryOrderId == inventoryorderId);
        int curentOrdQuantity = inventoryOrder.OrderQuantity;
        inventoryOrder.OrderQuantity = (int)orderedQuantity;
        _context.SaveChanges();

        var intData = await _context.Inventories.FindAsync(inventoryId);
        int availQty = intData.QuantityAvailable;
        if ((int)orderedQuantity > curentOrdQuantity)
        {
            if (availQty < ((int)orderedQuantity - curentOrdQuantity))
            {
                return Json(new { status = "NotAvailable", available = intData.QuantityAvailable });
            }
            else
            {
                //Updating the Order
                inventoryOrder.OrderQuantity = (int)orderedQuantity;
                _context.Update(inventoryOrder);
                await _context.SaveChangesAsync();

                //Updating Inventory
                intData.QuantityAvailable = intData.QuantityAvailable - ((int)orderedQuantity - curentOrdQuantity);
                _context.Update(intData);
                await _context.SaveChangesAsync();                    
            }
        }
        else if ((int)orderedQuantity < curentOrdQuantity)
        {
            //Updating the Order
            inventoryOrder.OrderQuantity = (int)orderedQuantity;
            _context.Update(inventoryOrder);
            await _context.SaveChangesAsync();

            //Updating Inventory
            intData.QuantityAvailable = intData.QuantityAvailable + (curentOrdQuantity - (int)orderedQuantity);
            _context.Update(intData);
            await _context.SaveChangesAsync();                
        }
        return Json("");
    }

有两个问题

  1. 当输入的数量更多时,我正在尝试 return Json(new { status = "NotAvailable", available = intData.QuantityAvailable }); 但数据库中的 OrderQuantity 仍然更新为输入的新值。即使我没有更新代码中的订单,它也会更新为新输入的值。我怎样才能将它恢复到旧值而不更改输入的内容

  2. 当数量小于 QuantityAvailable 时,我将同时更新库存和订单并返回 return Json(""); 我希望导航回索引页面

           else if (result == "")  {
                 var url = '@Url.Action("Index", "Orders")';
                 window.location.href = url + "?custEmail=xy@rrr.org";
             }
    

但什么也没发生,它只是停留在 smae 页面中。任何人都可以帮助我在这里缺少什么

编辑 第一个问题已解决,但我仍然无法在 ajax 上获得 success() 工作 我尝试添加警报成功,但我的警报没有显示

     success: function (result) {
       alert(result);
                if (result !== "") {
                    if (result.available == "NotAvailable")
                        $("#errorMessage").val("Enter a valid Quantity");
                }
                else if (result == "")  {

型号Class

public class Order
{
    public int CustomerNumber { get; set; }
    public int CustomerId { get; set; }
    public int OrderId  { get; set; }
    public int InventoryId { get; set; }
    public int InventoryOrderId { get; set; }
    public string StrainId { get; set; }
    public string StrainName { get; set; }
    public string StrainCode { get; set; }
    public string Age { get; set; }
    public string Sex { get; set; }
    public string Genotype { get; set; }
    public int QuantityAvailable { get; set; }
    public int OrderQuantity { get; set; }
    public string RoomNumber { get; set; }
}

第一期

你总是更新数据库,你的方法的第一行获取 InventoryOrder 并更新该行,我注释掉了代码

public async Task<JsonResult> EditItem(int? orderId, int? inventoryorderId, int? inventoryId, int? orderedQuantity)
    {
        var inventoryOrder = await _context.InventoryOrders
            .FirstOrDefaultAsync(io => io.InventoryOrderId == inventoryorderId); // Get the InventoryOrder
        int curentOrdQuantity = inventoryOrder.OrderQuantity; // Save the currentOrdQUantity
        inventoryOrder.OrderQuantity = (int)orderedQuantity; // UPDATE the OrderQuantity
        _context.SaveChanges(); // <- Persist to DB

第二期

我建议你在success: function (result) {

后面加一个console.log(result);

考虑

  • 通过 Nullable,您可以使用 .Value 来访问值,即 orderId.Value 而不是 (int)orderId

  • 由于您传递了 nullable 值,请考虑在转换或读取值之前检查是否为 null

恕我直言,您不需要 ajax 这个

查看

@model CustomerInventoryModel

form asp-controller="Orders" asp-action="EditItem" method="post">

...... other use controls

    <div class="form-group">
                <label asp-for="Inventory.QuantityAvailable" class="control-label" readonly></label>
                <input asp-for="Inventory.QuantityAvailable "  class="form-control" />
       </div>

    <div class="form-group">
        <label asp-for="Inventory.QuantityReq" class="control-label"></label>
        <input asp-for="Inventory.QuantityReq" class="form-control" />
        <input value="@Model.Inventory.ErrorMessage" class="form-control text-danger float-right" style="border:none;font-size: smaller" />
    </div>
    
    <input type="hidden" asp-for="CustomerId" value="@Model.CustomerId" />
    <input type="hidden" asp-for="Inventory.InventoryId" value="@Model.Inventory.InventoryId" />
    <div>
        <button id="buyNow" type="submit">  Buy now </button>
    </div>

</form>

将 ErrorMessage 属性 添加到清单 class

public partial class Inventory
{
    public int InventoryId { get; set; }
   ......
   
     [NotMapped]
    public string ErrorMessage{ get; set; }

    [NotMapped]
    public int? QuantityReq { get; set; }
}

并创建详细视图模型

public class CustomerInventoryModel
{
        public  int CustomerId { get; set; }
        public Inventory Inventory { get; set; }
}

行动

public async Task<ActionResult> OrderItem(CustomerInventoryModel model)
{
    
    Customer custData = await _context.Customers.FindAsync(model.CustomerID);
    var intData = await _context.Inventories.FindAsync(model.Inventory.InventoryID);

        if (model.Inventory.QuantityReq <= intData.QuantityAvailable)
        {
           ... your code  

          return Redirect("Index", new {id=model.CustomerId} );             
        }
       
          model.ErrorMessage("not enough")
         return View(model);
}