skip to Main Content

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" 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 + "[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 == "")  {

Model 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; }
}

2

Answers


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

    Login or Signup to reply.
  2. IMHO you don’t need ajax for this

    view

    @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>
    

    add ErrorMessage property to Inventory class

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

    and create a detail view model

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

    action

    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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search