2013-12-19 102 views
0

我一直試圖在c#asp.net和SQL服務器中創建購物車沒有成功。如何在購物車中使用會話變量

我能夠從數據庫檢索產品併爲每個產品創建詳細視圖。

現在我需要創建按鈕「添加到購物車」,我知道我必須創建一個數組的會話變量來保存產品信息,然後顯示在購物車中,但我不知道如何。

這是我在productsDetail.cs代碼:

protected void Page_Load(object sender, EventArgs e) 
    { 
     SqlConnection connexionBD = new SqlConnection(this.data_un_jouet.ConnectionString); 

     SqlCommand commandeJouets = null; 

     SqlDataReader lecteurJouets = null; 

     try 
     { 
      connexionBD.Open(); 

      String id = Request.QueryString["no"]; 

      Session["product"] = id; 

      string myQuery = data_un_jouet.SelectCommand; 

      commandeJouets = new SqlCommand(myQuery, connexionBD); 

      commandeJouets.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(id); 

      lecteurJouets = commandeJouets.ExecuteReader(); 

      TableRow uneLigne; 
      TableCell uneCellule; 

      while (lecteurJouets.Read()) 
      { 
       uneLigne = new TableRow(); 
       string myID = Convert.ToString(lecteurJouets["id"]); 

       uneCellule = new TableCell(); 
       uneCellule.Text = Convert.ToString(lecteurJouets["name"]); 
       uneLigne.Cells.Add(uneCellule);      

       uneCellule = new TableCell(); 
       uneCellule.Text = "<img src=" + lecteurJouets["image"].ToString() + "/>"; 
       uneLigne.Cells.Add(uneCellule); 

       uneCellule = new TableCell(); 
       uneCellule.Text = Convert.ToString(lecteurJouets["description"]); 
       uneLigne.Cells.Add(uneCellule); 

       uneCellule = new TableCell(); 
       uneCellule.Text = Convert.ToString(lecteurJouets["price"]); 
       uneLigne.Cells.Add(uneCellule); 

       uneCellule = new TableCell(); 
       uneCellule.Text = "<a href=\"cart.aspx?no=" + myID + "\" />Add to cart</a>"; 
       uneLigne.Cells.Add(uneCellule); 

       this.un_jouet.Rows.Add(uneLigne); 
      } 

      lecteurJouets.Close(); 
      commandeJouets.Dispose(); 
     } 
     catch (Exception ex) 
     { 
      msgErreur.Text = "Erreur de connexion ! " + ex.Message; 
     } 
     finally 
     { 
      connexionBD.Close(); 
     } 

我知道的大部分代碼是法語,我試着翻譯了一些。

此代碼工作得很好,問題是我不知道點擊「添加到購物車按鈕」時該怎麼辦。

我創建了一個會話變量,但它只包含產品ID。

非常感謝您的幫助,

回答

0

就像你說的,你需要將數組分配到會話。更好的是,使用列表,因爲你沒有固定數量的項目。假設我們將商品的ID存儲在購物車中,並且這些ID是整數。所以首先我們需要實例化List。有很多地方可以做到這一點,但現在Page_Load事件沒有問題。

If (Session["ShoppingCart"] == null) 
{ 
    Session["ShoppingCart"] = new List<int>(); 
} 

我們首先檢查我們是否已經分配了會話變量,如果沒有,我們這樣做。

然後當客戶添加到購物車的商品(比如按下一個按鈕),你需要把這個添加到代碼中處理該事件:

var products = (List<int>)Session["ShoppingCart"]; 
products.Add(newProductId); 

我沒有在這裏做什麼(和你應該)檢查會話變量實際上有一個List以避免錯誤。請記住,會話不是強類型的。

爲了更好,更乾淨的代碼,您應該將會話封裝在自己的get/set屬性中。

+0

非常感謝您的幫助@System Down 我已經在details.cs的頁面加載聲明瞭產品列表 運行程序時出現此錯誤:「對象引用未設置爲對象的實例「。它來自我將我的ID添加到列表中的行:「products.Add(myID);」 我已經添加了條件來檢查會話是否存在於cart.cs中我猜我需要循環列表來檢索產品,但我不知道如何,我知道這是很多要問,但任何幫助對我來說是美好的。 – Xavieres