0

here I updated my quantity. how I will use or inject this updated quantity?




        [HttpGet]

        public ActionResult Details(int? id)
        {
            ViewBag.product = _db.Spray.ToList();
            if (id == null)
            {
                return NotFound();
            }

            var hi = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);

            ProductVm product = new ProductVm
            {
                Name = hi.Name,
                Id = hi.Id,
                Image=hi.Image,
                Image1=hi.Image1,
                Quantity = hi.Quantity,
                Price = hi.Price,
            };
           

            if (product == null)
            {
                return NotFound();
            }

            return View(product);
        }



        [HttpPost]
        [ActionName("Details")]

        public async Task <IActionResult> ProductDetails(ProductVm pb)
        {

            List<Spray> sprays = new List<Spray>();

            //if (id == null)
            //{
            //    return NotFound();
            //}

            //var yes = _db.Spray.Include(c => c.ProductTypes).FirstOrDefault(c => c.Id == id);


            ProductVm product = new ProductVm()
            {
                Name = pb.Name,
                Id = pb.Id,
                Image = pb.Image,
                Image1=pb.Image1,
                Quantity = pb.Quantity,
                Price = pb.Price,
             
            };
          

            if (product == null)
            {
                return NotFound();
            }
            sprays = HttpContext.Session.Get<List<Spray>>("sprays");
            if (sprays == null)
            {
                sprays = new List<Spray>();
            }
            sprays.Add(product);
            HttpContext.Session.Set("sprays", sprays);

            return RedirectToAction(nameof(Index));
        }


        [HttpGet]
        public IActionResult Cart()
        {

            List<Spray> sprays = HttpContext.Session.Get<List<Spray>>("sprays");
           
            
            if (sprays == null)
            {
                sprays = new List<Spray>();
            }
            return View(sprays);
        }



@model List<Spray>
@{
    ViewData["Title"] = "Cart";
}

<div>
    <div class="row">
        <div class="col-6">
            <table class="table table-bordered">
                <thead>
                    <tr>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Quantity</th>
                        <th>Price</th>
                        <th>Quantity Update</th>
                        <th>Total</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>
                                <img src="~/@item.Image" width="200px" height="150px" />
                            </td>
                            <td>@item.Name</td>

                            <td>@item.Quantity</td>
                            <td>@item.Price</td>
                            <td>
                                <input type="number" asp-for="@item.Quantity" min="0" max="1000" />
                            </td>

                            <td>@(item.Price * item.Quantity)</td>
                            <td>
                                <a asp-area="Customer" asp-action="Remove" asp-controller="LaptopShow" asp-route-id="@item.Id" class="btn btn-danger">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        </div>
        <div class="col-6">
            <div class="text-right">
                <h3>Total Amount</h3>
                <h3>Grand Total : @Model.Sum(c => c.Price * c.Quantity)</h3>
                <a asp-area="Customer" asp-action="Checkout" asp-controller="Order" class="btn btn-info">Process To CheckOut</a>
            </div>
        </div>
        <div>
            <a asp-action="Index" asp-controller="SprayShow" class="btn btn-primary">Back To Home</a>
        </div>
    </div>
</div>
@*<div>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
    <a asp-action="Index">Back to List</a>
</div>*@
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
    $(function () {
        $("input[name='item.Quantity']").change(function () {
            //get the new quantity
            var newquantity = parseInt($(this).val());
            //update the original quantity value
            $(this).closest("tr").find("td")[2].innerHTML = newquantity;

            //get the price
            var price = parseFloat($(this).closest("tr").find("td")[3].innerHTML);
            //calculate the total
            $(this).closest("tr").find("td")[5].innerHTML = newquantity * price;

            //calcule the Grand Total
            var grandtotal = 0;
            $("tbody").find("tr").each(function (index, item) {
                var value = parseFloat($(item).find("td")[5].innerHTML);
                grandtotal += value;
            });
            $(".text-right h3:last").html("Grand Total : " + grandtotal.toString());
        });
    });
</script>

above code, I change quantity increase and decrease for calculating.but this update value session data could not pick. for that, I am found a problem here to process to checkout problem. I can not found actual quantity data which I updated cart.cshtml. here my output the updated the quantity using jquery enter image description here


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using HuddsonBay.Data;
using HuddsonBay.Models;
using HuddsonBay.Utility;
using Microsoft.AspNetCore.Mvc;

namespace HuddsonBay.Areas.Customer.Controllers
{
    [Area("Customer")]
    public class OrderController : Controller
    {
        private ApplicationDbContext _db;

        public OrderController(ApplicationDbContext db)
        {
            _db = db;
        }

        [HttpGet]
        public IActionResult Checkout()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Checkout(Order anOrder)
        {
            //session theke data peck

            List<Spray> sprays = HttpContext.Session.Get<List<Spray>>("sprays");

            if (sprays != null)
            {
                for each (var mobile in sprays)
                {
                    OrderDetails orderDetails1 = new OrderDetails();
                    orderDetails1.ProductId = mobile.Id;
                    anOrder.OrderDetails.Add(orderDetails1);
                }
            }
            anOrder.OrderNo = GetOrderNo();
            _db.Orders.Add(anOrder);
            await _db.SaveChangesAsync();
            HttpContext.Session.Set("sprays", new List<Spray>());

            return RedirectToAction(nameof(Checkout));
        }

        public String GetOrderNo()    //for count order number
        {
            int rowCount = _db.Orders.ToList().Count() + 1;
            return rowCount.ToString("000");
        }
    }
}

above view, the list of item session data can not pick my updated quantity. how I solved this problem. I am facing problem in order of the value of the quantity. I am beginner, please anyone help. enter image description here

5
  • @Pirom I would recommend trying rewording your question. As a reader I don't understand what you are asking so I don't know how to help. Commented Aug 5, 2020 at 18:51
  • Your code that picks up the next order number is wrong, it will fail in concurrent environment by creating duplicate order numbers. Please use a database sequence to reliably generate unique order numbers. Commented Aug 5, 2020 at 20:37
  • how?is there is no way to solve this problem? Commented Aug 5, 2020 at 20:40
  • Where do you add List<Spray>sprays to session?Without session,you can also use ajax to pass data to controller. Commented Aug 6, 2020 at 4:01
  • @yiyi I add list in the controller. I would really glad if you explain the ajax of this code and post controller. Commented Aug 6, 2020 at 4:53

1 Answer 1

1

Here is a demo to show how to pass List to controller with ajax:

Spray:

public class Spray
    {
        public int Id { get; set; }
        public string Image { get; set; }
        public string Name { get; set; }
        public int Quantity { get; set; }
        public int Price { get; set; }
        public int Total { get; set; }
    }

Controller:

 [HttpGet]
        public IActionResult Cart()
        {
            List < Spray > sprays= new List<Spray> { new Spray { Id = 1, Name = "product1", Price = 10, Quantity = 1, Total = 1,Image="image1.png" }, new Spray { Id = 2, Name = "product2", Price = 20, Quantity = 1, Total = 20,Image="Image2.png" } };
            return View(sprays);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> SendSprays([FromBody]IList<Spray> t) {
            return RedirectToAction(nameof(Cart));
        }

Cart.cshtml:

<div>
        <div class="row">
            <div class="col-6">
                <table class="table table-bordered" id="myTable">
                    <thead>
                        <tr>

                            <th>Image</th>
                            <th>Name</th>
                            <th>Quantity</th>
                            <th>Price</th>
                            <th>Quantity Update</th>
                            <th>Total</th>
                            <th></th>
                            <th hidden>Id</th>
                            <th hidden>ImageValue</th>
                        </tr>
                    </thead>
                    <tbody>
                       
                        @foreach (var item in Model)
                            {
                        <tr>

                            <td>
                                <img src="~/@item.Image" width="200px" height="150px" />
                            </td>
                            <td>@item.Name</td>
                            <td>@item.Quantity</td>
                            <td>@item.Price</td>
                            <td>
                                <input type="number" asp-for="@item.Quantity" min="0" max="1000" />
                            </td>

                            <td>@(item.Price * item.Quantity)</td>
                            <td>
                                <a asp-area="Customer" asp-action="Remove" asp-controller="LaptopShow" asp-route-id="@item.Id" class="btn btn-danger">
                                    <i class="fas fa-trash"></i>
                                </a>
                            </td>
                            <td hidden>@item.Id</td>
                            <td hidden>@item.Image</td>
                        </tr>
                            }
                    </tbody>
                </table>
            </div>
            <div class="col-6">
                <div class="text-right">
                    <h3>Total Amount</h3>
                    <h3>Grand Total : @Model.Sum(c => c.Price * c.Quantity)</h3>
                    <button  onclick="checkout()">Process To CheckOut</button>
                    @*<a asp-action="Checkout" asp-controller="Test" class="btn btn-info">Process To CheckOut</a>*@
                </div>
            </div>
            <div>
                <a asp-action="Index" asp-controller="SprayShow" class="btn btn-primary">Back To Home</a>
            </div>
        </div>
    </div>

@*<div>
        @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
        <a asp-action="Index">Back to List</a>
    </div>*@
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
    $(function () {
        $("input[name='item.Quantity']").change(function () {
            //get the new quantity
            var newquantity = parseInt($(this).val());
            //update the original quantity value
            $(this).closest("tr").find("td")[2].innerHTML = newquantity;
            //get the price
            var price = parseFloat($(this).closest("tr").find("td")[3].innerHTML);
            //calculate the total
            $(this).closest("tr").find("td")[5].innerHTML = newquantity * price;
            //calcule the Grand Total
            var grandtotal = 0;
            $("tbody").find("tr").each(function (index, item) {
                var value = parseFloat($(item).find("td")[5].innerHTML);
                grandtotal += value;
            });
            $(".text-right h3:last").html("Grand Total : " + grandtotal.toString());
        });

    });
    function checkout() {
        var oTable = document.getElementById('myTable');

        //gets rows of table
        var rowLength = oTable.rows.length;
        var sprays = new Array();
        //loops through rows
        for (i = 1; i < rowLength; i++) {
            var tempspray = {};
            //gets cells of current row
            var oCells = oTable.rows.item(i).cells;

            //gets amount of cells of current row
            var cellLength = oCells.length;
            //tempspray.image = oCells.item(j).
            
            tempspray.Name = oCells.item(1).innerHTML;
            tempspray.Quantity = parseInt(oCells.item(2).innerHTML);
            tempspray.Price = parseInt(oCells.item(3).innerHTML);
            tempspray.Total = parseInt(oCells.item(5).innerHTML);
            tempspray.Id = parseInt(oCells.item(7).innerHTML);
            tempspray.Image = oCells.item(8).innerHTML;
            sprays.push(tempspray);
        }
        
        
        var token = $('input[name="__RequestVerificationToken"]').val();
        var t = JSON.stringify(sprays);
         $.ajax({
        type: "POST",
        url: '@(Url.Action("SendSprays", "Test"))',
        headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
            data: t,
            contentType: "application/json; charset=utf-8"
        });
      
    }
</script>

result: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.