2013-12-19 3 views
0

저는 C# asp.net 및 SQL 서버에서 장바구니를 만들려고 노력했습니다.장바구니에서 세션 변수를 사용하는 방법

데이터베이스에서 제품을 검색하고 각 제품에 대한 상세보기를 만들 수있었습니다.

지금은 "장바구니에 추가"버튼을 만들 필요가 있습니다. 제품 정보를 저장하고 장바구니에 표시 할 배열이있는 세션 변수를 만들어야한다는 것을 알고 있지만 어떻게해야할지 모르겠다. . 나는 코드의 대부분은 프랑스어로, 나는 그것의 일부를 번역 해봤 알고

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(); 
     } 

:

이것은 productsDetail.cs 내 코드입니다.

이 코드는 정상적으로 작동하지만 문제는 "장바구니에 추가 버튼"을 클릭했을 때 어떻게 해야할지 모르겠다는 것입니다.

세션 변수를 만들었지 만 제품 ID 만 포함되어 있습니다.

답변

0

은 마찬가지로 당신은 당신이 세션에 배열을 할당 할 필요가 말했다, 당신의 도움을 주셔서 감사합니다. 목록의 개수는 고정되어 있지 않으므로 목록을 사용하는 것이 좋습니다. 장바구니에 상품의 ID를 저장하고 해당 ID가 int라고 가정 해 봅시다. 먼저 목록을 인스턴스화해야합니다. 이 작업을 수행 할 수있는 곳이 많이 있지만 지금은 Page_Load 이벤트가 좋습니다.

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

먼저 세션 변수를 할당했는지 확인하고 그렇지 않은 경우 확인합니다.

그런 다음 고객이 장바구니에 항목을 (예를 들어이 버튼을 누르면), 해당 이벤트를 처리하는 코드에 이것을 추가해야합니다 추가 할 때 :

내가 여기하지 않은 무엇
var products = (List<int>)Session["ShoppingCart"]; 
products.Add(newProductId); 

(그리고 당신은) 세션 변수를 실제로 확인하는 것입니다 오류를 피하기 위해 목록이 있습니다. 세션은 강하게 입력되지 않는다는 것을 기억하십시오.

더 깔끔하고 깨끗한 코드를 얻으려면 세션을 자체 get/set 속성으로 캡슐화해야합니다.

+0

대단히 감사합니다. @System Down 페이지로드시 details.cs의 제품 목록에 제품 목록을 선언했습니다. 프로그램을 실행할 때이 오류가 발생합니다. "개체 참조가 개체의 인스턴스로 설정되지 않았습니다. . " 그것은 내 ID를 목록에 추가하는 줄에서옵니다 : "products.Add (myID);" 세션이 cart.cs에 있는지 확인하기 위해 조건을 추가했습니다. 제품을 검색하기 위해 목록을 반복 할 필요가 있다고 생각하지만 아이디어가 없습니다. 방법은 많이 있지만 도움은 많이 필요하다는 것을 알고 있습니다. 나에게 경이 롭다. – Xavieres

관련 문제