2011-04-30 107 views
1

我用這個例子來創建一個購物車: http://net.tutsplus.com/tutorials/other/build-a-shopping-cart-in-aspnet/經典asp.net購物車會話狀態

它的一個很好的例子,它存儲了我的購物會話[「購物車」]的狀態,它應該所有的工作精細。

但它沒有。事件如果關閉瀏覽器,或嘗試不同的瀏覽器,它仍然保持狀態?!?!

這裏的構造函數+的添加到購物車方法:

public List<CartItem> Items { get; private set; } 

     // Readonly properties can only be set in initialization or in a constructor 
     public static readonly ShoppingCart Instance; 
     // The static constructor is called as soon as the class is loaded into memory 
     static ShoppingCart() 
     { 
      // If the cart is not in the session, create one and put it there 
      // Otherwise, get it from the session 
      if (HttpContext.Current.Session["MPBooksCart"] == null) 
      { 
       Instance = new ShoppingCart(); 
       Instance.Items = new List<CartItem>(); 
       HttpContext.Current.Session["MPBooksCart"] = Instance; 
      } 
      else 
      { 
       Instance = (ShoppingCart)HttpContext.Current.Session["MPBooksCart"]; 
      } 
     } 
     // A protected constructor ensures that an object can't be created from outside 
     protected ShoppingCart() { } 

     public void AddItem(int book_id) 
     { 
      // Create a new item to add to the cart 
      CartItem newItem = new CartItem(book_id); 
      // If this item already exists in our list of items, increase the quantity 
      // Otherwise, add the new item to the list 
      if (this.Items.Contains(newItem)) 
      { 
       foreach (CartItem i in Items) 
       { 
        if (i.Equals(newItem)) 
        { 
         i.Quantity++; 
         return; 
        } 
       } 
      } 
      else 
      { 
       newItem.Quantity = 1; 
       Items.Add(newItem); 
      } 

     } 

願請指教什麼問題可能是什麼?

我已經閱讀了約2小時關於會話狀態和它說它應該是揮發性關閉broser時,但在這種情況下,它不是。

問候, 亞歷

回答

1

我不是很確定使用Singleton模式舉行會議的一個實例。如果您仔細考慮,會話對於訪問該網站的每個用戶和每個瀏覽器都必須是唯一的。 Singleton模式創建一個全局唯一的實例。我不知道你已經做了多少asp.net,但是,如果你對asp.net相當陌生,會話對於特定的瀏覽器實例將是唯一的。這意味着訪問Session [「MPBooksCart」]的每個瀏覽器都將訪問他們自己的唯一數據副本。默認情況下,一個asp.net會話將保存20分鐘的數據(這可以在數據庫中配置)。 如果我正在寫購物車,我很可能會直接使用數據庫中的購物車表和cartitems表。店面網站的一個很好的例子是Rob Connery的MVC Samples App。這是一個ASP.Net MVC應用程序,所以如果你不熟悉MVC,你可能會發現這有點難以遵循。

+0

嗨安德魯,謝謝你的迴應。我對ASP.net相當陌生。我認爲單身人士也是這樣的錯。這裏只是我正在構建的圖書網站的預覽版,你可以親自看到這個版本不起作用。如果您點擊圖書價格下的購買鏈接,它將執行ajax流程來更新會話狀態並將總項目放在白色菜單上方。如果你關閉瀏覽器,你會看到數字相同或更高。 http://mp-books.ru/html/ – 2011-04-30 12:32:42

+0

@亞歷山大,不幸的是,我的俄語並不像你的英語那麼好。我喜歡你的設計。查看網上購物車的其他一些示例。我喜歡ASP.Net webforms(經典)的一個是Microsoft的.Net PetShop 4.0示例應用程序。 – Andrew 2011-05-01 09:16:38