session + List<T> 實現購物車(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);
	            }
	        });
	    }
	});






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章