簡體   English   中英

從 ViewModel 更新 session 數據

[英]update session data from ViewModel

在這里我更新了我的數量。 我將如何使用或注入這個更新的數量?




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

上面的代碼,我改變了數量的增加和減少來計算。但是這個更新值 session 數據無法選擇。 為此,我在這里發現了一個問題來處理結帳問題。 我找不到更新 cart.cshtml 的實際數量數據。 這里我的 output 使用 jquery 更新了數量在此處輸入圖像描述


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

上面的視圖,項目列表 session 數據無法選擇我更新的數量。 我是如何解決這個問題的。 我按照數量的價值順序面臨問題。 我是初學者,請任何人幫助。 在此處輸入圖像描述

這是一個演示如何使用ajax將List傳遞給controller:

噴:

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

控制器:

 [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));
        }

購物車.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>

結果: 在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM