必要的:Asp.net MVC 5 购物车在会话中选择的项目

necessary: Asp.net MVC 5 Shopping Cart selected items in Session

我创建一个购物车控制器并使用 Web 查看 Api 我使用 Session (HttpContext.Current.Session) 并且我想对所选项目使用 Ajax 这是我的网站 Api ShoppingCartController:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using System.Web.Routing ;
using WebApplication4.Models ;
using WebApplication4 ;

namespace WebApplication4.Controllers
{
    public class ShoppingCartApiController : ApiController
    {
        // GET api/shoppingcartapi
        public int Get()
        {
            int cartitemscount = 0;
            var Sessions = HttpContext.Current.Session;
            if (Sessions["ShoppingCartItems"] != null)
            {
                List<ProductInShoppingCart> product = Sessions["ShoppingCartItems"] as List<ProductInShoppingCart>;

                foreach (var productInShoppingCart in product)
                {
                    cartitemscount+=productInShoppingCart.ProductCount;
                }

            }
            return cartitemscount;
        }

        // GET api/shoppingcartapi/5
        public int Get(int productID)
        {
            int cartitemscount = 0;
            var Session = HttpContext.Current.Session;
            List<ProductInShoppingCart> product = new List<ProductInShoppingCart>();
            if (Session["ShoppingCartItems"]!=null)
            {
                product = Session["ShoppingCartItems"] as List<ProductInShoppingCart>;
                ProductInShoppingCart selected = product.Find(p => p.ProductId == productID);
                if (selected!=null)
                {
                    selected.ProductCount++;
                    int index = product.FindIndex(p => p.ProductId == productID);
                    product[index] = selected;
                }
            else
                {
                    selected = new ProductInShoppingCart(){ProductId = productID ,ProductCount = 1};
                    product.Add(selected);
                }
                Session["ShoppingCartItems"] = product;
            }
            else
            {
                ProductInShoppingCart selected = new ProductInShoppingCart(){ProductId = productID , ProductCount = 1};
          product.Add(selected);
                Session["ShoppingCartItems"] = product;
            }
            foreach (var productInShoppingCart in product)
            {
                cartitemscount += productInShoppingCart.ProductCount;
            }
            return cartitemscount;
        }
        }
    }

这是我在 ProductList 中的观点:

    @model List<WebApplication4.Models.Product>

@{
    ViewBag.Title = "List";
    Layout = "~/Views/Shared/_Layout.cshtml";
    <script src="~/Scripts/jquery-2.1.1.js"></script>
}
<style type="text/css">
    .ProductItem {
        text-align: center;
        padding-bottom: 10px;
        min-height: 150px;
    }
</style>
<h2>List</h2>
<div class="row">
    @foreach (var item in Model)
    {
        <div class="col-md-4 ProductItem">
            <div class="row">
                <div class="col-md-12">
                    @item.ProductTitle
                </div>
                <div class="col-md-12">
                    <img src="@item.ProductThumbnailImageUrl" class="img-thumbnail" />
                </div>
                <div>
                   Price : @item.ProductPrice.ToString("#,0ریال")
                </div>
            </div>
            <div class="col-md-12">
                <input type="button" class="btn btn-default" value="Add To Basket"id="btnAddToBasket_@item.ProductID " />
            </div>
        </div>
    }


</div>
<script type="text/javascript" language="javascript">
  $(document).ready(function () {
        $("[id=btnAddToBasket]").each(function () {
            $(this).click(function () {
                var productID = $(this).attr("id").match(/[\d]+$/);
                $.ajax({
                    url: "/api/ShoppingCartApi",
                    data: { productID: productID },
                    type: "GET"
                }).done(function (result) {
                    if (result) {
                        $("#cartinfo").fadeOut(200).html("Selected Items: " + result).fadeIn(200);
                    }
                    else {
                    }
                });

            });
        });
    });
</script>

这是布局中的 cartinfo:

<a href="/ShoppinCart">
            <div id="cartinfo" style="position: absolute; top: 15px; left: 5px; padding: 10px; background-color: greenyellow; border-radius: 7px 7px 7px 7px;" title="مشاهده سبد خرید ">
                Selected Items : 0
            </div>
        </a>

当我点击 AddToBasket 按钮时必须将该项目添加到会话,但它不起作用

这里是 ShoppingCartController:

    using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using eShopMVC;
using eShopMvc.Models;
using Kendo.Mvc.UI.Fluent;
using WebApplication4.Models;

namespace WebApplication4.Controllers
{
    public class ShoppinCartController : Controller
    {
        private eShopMVCEntities db = new eShopMVCEntities();

        // GET: ShoppinCart
        public ActionResult Index()
        {
            List<ShoppinCartView> cartcontents = new List<ShoppinCartView>();
            if (Session["ShoppingCartItems"] != null)
            {
                List<ProductInShoppingCart> producInCart = Session["ShoppingCartItems"] as List<ProductInShoppingCart>;
                var dbProduct = db.Products.ToList();
                cartcontents = (from pr in dbProduct
                    join pic in producInCart on pr.ProductID equals pic.ProductId
                    select new ShoppinCartView
                    {
                        ProductID = pr.ProductID,
                        ProductTitle = pr.ProductTitle,
                        ProductPrice = pr.ProductPrice,
                        ProductCount = pic.ProductCount,
                        RowTotal = pr.ProductPrice*pic.ProductCount

                    }).ToList();
                return View(cartcontents);
            }
            return View(cartcontents);
        }


        // GET: ShoppinCart/SubCount
        public ActionResult SubCount(int id)
        {
            if (Session["ShoppingCartItems"] != null)
            {
                List<ProductInShoppingCart> productincart = Session["ShoppingCartItems"] as List<ProductInShoppingCart>;

                int index = productincart.FindIndex(p => p.ProductId == id);
                ProductInShoppingCart item = productincart[index];
                if (item.ProductCount == 1)
                {
                    productincart.RemoveAt(index);
                }
                else
                {
                    item.ProductCount--;
                    productincart[index] = item;
                }
                Session["ShoppingCartItems"] = productincart;

            }
            return RedirectToAction("index");
        }

        public ActionResult AddCount(int id)
        {
            if (Session["ShoppingCartItems"] != null)
            {
                List<ProductInShoppingCart> productincart = Session["ShoppingCartItems"] as List<ProductInShoppingCart>;
                int index = productincart.FindIndex(p => p.ProductId ==id);
                productincart.RemoveAt(index);
                Session["ShoppingCarttems"] = productincart;
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id)
        {
             if (Session["ShoppingCartItems"] != null)
            {
                List<ProductInShoppingCart> productsInCart = Session["ShoppingCartItems"] as List<ProductInShoppingCart>;
                int index = productsInCart.FindIndex(p => p.ProductId == id);
                productsInCart.RemoveAt(index);
                Session["ShoppingCartItems"] = productsInCart;
            }
            return RedirectToAction("Index");

        }
        [Authorize]
        public ActionResult finalize()

        {
            List<ShoppinCartView> cartcontent = new List<ShoppinCartView>();
            if (Session["ShoppingCartItems"] != null)
            {
                List<ProductInShoppingCart> productincart = Session["ShoppingCartItems"] as List<ProductInShoppingCart>;
                var dbproduct = db.Products.ToList();
                cartcontent = (from pr in dbproduct
                    join pic in cartcontent on pr.ProductID equals pic.ProductID
                    select new ShoppinCartView
                    {
                        ProductID = pr.ProductID,
                        ProductTitle = pr.ProductTitle,
                        ProductPrice = pr.ProductPrice,
                        ProductCount = pic.ProductCount,
                        RowTotal = pr.ProductPrice*pic.ProductCount
                    }).ToList();
                string username = User.Identity.Name;
                int userid = db.Users.Where(p => p.Username == username).FirstOrDefault().UserID;
                Order order = new Order()
                {
                    UserID = userid,
                    OrderDate = DateTime.Now,
                    IsFinalized = false

                };
                db.Orders.Add(order);
                foreach (ShoppinCartView item in cartcontent)
                    db.OrderDetails.Add(new OrderDetail()
                    {
                        OrderID = order.OrderID,
                        ProductID = item.ProductID,
                        OrderedCount = item.ProductCount
                    });

                db.SaveChanges();

                Session["ShoppingCartItems"] = null;
            }
            return RedirectToAction("index");
        }

        public ActionResult Orders()
        {
            string username = User.Identity.Name;
            int userid = db.Users.Where(p => p.Username == username).FirstOrDefault().UserID;
            var userorders = (from o in db.Orders
                where o.UserID == userid
                select new OrderView()
                {
                    OrderId = o.OrderID,
                    OrderDate = o.OrderDate,
                    IsFinalized = o.IsFinalized,
                    OrderTotal = (from od in db.OrderDetails
                        join p in db.Products on od.ProductID equals p.ProductID
                        where od.OrderID == o.OrderID
                        select p.ProductPrice*od.OrderedCount
                        ).Sum(),
                    OrderDetails = (List<OrderDetail>) o.OrderDetails
                }).ToList();
            return View(userorders);
        }

        public ActionResult OnlinePayment(int id)
        {
            int ordertotal = (from od in db.OrderDetails
                join p in db.Products on od.ProductID equals p.ProductID
                where od.OrderID == id
                select od.OrderedCount*p.ProductPrice).Sum();
            BankParsianPayment bpp = new BankParsianPayment();
            PaymentUniqueNumber pun = new PaymentUniqueNumber() {OrderID = id};
            db.PaymentUniqueNumbers.Add(pun);
            db.SaveChanges();
            bpp.ProcessPayment(ordertotal, pun.PaymentUniqueID);
            return null;
            View();
        }

        public ActionResult ProcessOnlinePayment(int OID, string au, string rs)
        {
            int pun = OID;
            var orderid = (from pu in db.PaymentUniqueNumbers
                where pu.PaymentUniqueID == pun
                select pu.OrderID).FirstOrDefault();
            var ordertotal = (from od in db.OrderDetails
                join pr in db.Products on od.ProductID equals pr.ProductID
                where od.OrderID == orderid
                select od.OrderedCount*pr.ProductPrice).Sum();
            BankParsianPayment bpp = new BankParsianPayment();
            PaymentResponse Paymentresponse = bpp.ProcessResponse(au, rs, ordertotal, OID);
            db.PaymentLogs.Add(new PaymentLog()
            {
                IsSuccessful = Paymentresponse.Successful,
                PaymentDate = DateTime.Now,
                PaymentResponseCode = Paymentresponse.ResponseCode.ToString(),
                PaymentResponseMessage = Paymentresponse.ResponseMessage,
                TrackingCode = Paymentresponse.Transaction_ID,
                OrderID = orderid
            });
            if (Paymentresponse.Successful)
            {
                db.Orders.Where(o => o.OrderID == orderid).FirstOrDefault().IsFinalized = true;
            }
            db.SaveChanges();
            return View(Paymentresponse);
        }
    }
}

您的代码存在不少问题。将来我会尝试自己进行一些调试,例如使用 console.debug() 或在 post 提出这样的问题之前使用浏览器开发人员工具中的调试器。

第一个问题是:

$("[id=btnAddToBasket]").each(function () {

这只会获取 ID 为 btnAddToBasket 的所有按钮,但按钮 ID 的格式为 btnAddToBasket_[id],其中 [id] 是 ID。

所以您应该使用 ^=:

开头
$("[id^='btnAddToBasket']").each(function () {

下一个问题是您 select productId 的正则表达式不正确。应该是:

var productID = $(this).attr("id").match(/\d+/)[0];

这是因为 match 将 return 正则表达式匹配的数组对象,其中第一个元素具有值。我还删除了 $,因为它不是必需的,它导致了问题,因为它只对 /g 全局匹配有用。

向服务器发送数据以添加项目时,您应该使用 put 或 post。我将代码更改为 post:

type: "POST"

然后更改您的 webapi 以通过 post:

接受数据
public int Post(int productID)

当 post 仅输入 ID 时,您可以将其添加到 url:

$.ajax({
  url: "/api/ShoppingCartApi/" + productID,
  type: "POST"
})

这是显示添加的简单 jsfiddle。如果您检查开发人员工具中的网络选项卡,您可以看到它 post正在处理数据

我假设您的 C# 代码没问题,但如果不是,您需要使用 visual studio 调试器进行调试。