2011-04-30 126 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