session + List 实现购物车(asp.net mvc)

毕业设计做电子商务网站,结果卡购物车的实现上卡了N久,以下是我的思路:

1.session 用于存储用户名和购物车

2.List <T>用于存储购物车对象

3.Ajax 传值

部分代码:

1. 购物车:

public class Cart(){
   public int cartId{get;set;}
   public int albumId{get;set;}
   public int quantity{get;set;}
}
2. 购物车实现:

   public string CartAdd(string albumId,string quantity)
        {
             if(session["username"]==null)
                  return RedictToAction("/Home/Login");
             int Id = int.Parse(albumId);
            int num = int.Parse(quantity);
            int cartid=0;
            string str = null;
            string username = Session["username"].ToString();
            tb_cart cart = new tb_cart();
              List<tb_cartDetails> shopcar = null;
            if (Session["shopcart"] == null)
            {
                shopcar = new List<tb_cartDetails>();
                cartDetail.cartId = cartid;
                cartDetail.albumId = Id;
                cartDetail.quantity = num;

                shopcar.Add(cartDetail);
                Session["shopcart"] = shopcar;
            }
            else {
                shopcar = Session["shopcart"] as List<tb_cartDetails>;
                for (int i = 0; i<shopcar.Count;i++ ) {
                    if (shopcar[i].albumId == Id)
                    {
                        shopcar[i].quantity = shopcar[i].quantity + num;
                        Session["shopcart"] = shopcar;
                        str = "e";
                    
                    }
                }
                if (str == "e")
                    return str;
                else {
                    cartDetail.cartId = cartid;
                    cartDetail.albumId = Id;
                    cartDetail.quantity = 
                    shopcar.Add(cartDetail);
                    Session["shopcart"] = shopcar;
                }
            }
  return "添加成功";

}

3.Ajax 传值

$("#addCart").click(function () {
	    if ($("#_username").is(":empty")) {
	        $("#warningModal").modal();
	        $("#modal_info").text("您还没登录,登录之后才可以对商品进行添加");//判断用户是否登录
	        return false
	    } else {
	        var jsonData = "{\"albumId\":\"" + $("#_number").text() + "\", \"quantity\":\""+ $("#qunatity").val() + "\"}";//构建json
	        $.ajax({
	            type:"post",
	            dataType: "text",
	            contentType: "application/json",
	            url: "/Cart/CartAdd",
	            data: jsonData,
	            success: function (data) {
	                alert(data);
	            }
	        });
	    }
	});






展开阅读全文

没有更多推荐了,返回首页