2013-12-19 101 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