Home > Net >  Button to Update the Order Quantity is not working as expected
Button to Update the Order Quantity is not working as expected

Time:11-03

I am trying to have a button that allows the users to update the Quantity of the items they ordered. When the users tries to update the Quantity that is more than what is available I need to do nothing and show an error message saying something like Entered Quantity is more than what is available and shouldn't update anything in the DB

The View

      <form asp-action="EditItem">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
         ..............
                       <!--<input type="text"  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   "[email protected]";
                }
            },
            error: function (error) {
                alert(error);
            }
        });
    });
    </script>
    }

Controller Action

    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("");
    }

There are two issue

  1. When the Quantity entered is more I am trying return Json(new { status = "NotAvailable", available = intData.QuantityAvailable }); but still the OrderQuantity in the database got updated to the new value that was entered. Even though I am not updating the Order in the code it got updated to newly entered value. How can I restore it to old value and not change what was entered

  2. when the Quantity is lesser than the QuantityAvailable I am updating both the inventory and the order and returning return Json(""); I was hoping to navigate back to the Index page

           else if (result == "")  {
                 var url = '@Url.Action("Index", "Orders")';
                 window.location.href = url   "[email protected]";
             }
    

but nothing happens it just stays in the smae page. Can anyone please help what I am missing here

EDIT The first issue is reolved but still I am not able to get the success() work on the ajax I tried to add alert in the success but my alert is not showing up

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

CodePudding user response:

First Issue

You always update the DB, the first rows of your method get the InventoryOrderand update the row, I commented out the code

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

Second Issue

I suggest you to add a console.log(result); after the success: function (result) {

Consideration

  • With the Nullable you can use the .Value for accessing the value i.e. orderId.Value instead of (int)orderId.

  • Since you pass nullable values consider checking if are null before casting or reading the value

  • Related