必要:Asp.net MVC 5购物车在Session中选择了项目

时间:2015-01-03 08:42:43

标签: jquery ajax asp.net-web-api asp.net-mvc-5 shopping-cart

我使用Web Api创建购物车控制器和视图 我使用Session(HttpContext.Current.Session),我想使用Ajax选择项目 这是我的Web 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 In Layout:

<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 Button时,必须将该项添加到Session但它不起作用

这是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);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您的代码存在很多问题。将来我会尝试一些你自己的调试,比如使用console.debug()或者在发布这样的问题之前在浏览器开发者工具中使用调试器。

第一个问题是:

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

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

所以你应该使用^=开头:

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

下一个问题是你的正则表达式选择productId是不正确的。它应该是:

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

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

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

type: "POST"

然后将您的webapi更改为通过post:

接受数据
public int Post(int productID)

仅发布ID时,您只需将其添加到网址:

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

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

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