如何在ASP / VB.NET中创建会话对象/字典



我在Python中这样做的方式是

Session["ShoppingCart"] = {}

然后,如果我将一个新项目添加到购物车并保存它,我会这样做:

# Python/Flask
item = "Apple"
price = 2
quantity = 1
# Check it's not already in there...
if item not in Session["ShoppingCart"]:
Session["ShoppingCart"][item] = {"price": price, "quantity": quantity}
else:
# If it already exists, then increment the quantity
Session["ShoppingCart"][item]["quantity"] += 1

我将如何在 ASPX 页面的 VB.NET 中执行相同的流?到目前为止想出了什么

'VB.NET'
Partial Class ShoppingCart
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("ShoppingCart") Is Nothing Then
Session("ShoppingCart") = New ArrayList
End If
Dim title As String = Request.QueryString("Title")
Dim price As String = Request.QueryString("Price")
Session("ShoppingCart").Add(title)
End Sub
End Class

如您所见,我只知道如何一次添加一个项目,而不是像项目这样的字典/对象。

但是,我不确定如何使用 VB.NET 创建字典,我的最终结果是使用 GridView 在 UI 中显示会话购物车。

数组列表不是字典,因此通过在会话中存储数组列表,您将自己限制在使用数组列表。您至少可以将购物车项存储在数组列表中,然后可以访问和索引它们。

Arraylist已经很老了,自从通用集合出现以来,我不再使用它了。当一个人可以拥有例如 List(Of Person( 时,我看不出 ArrayList 有任何用处 - 两者都将存储一个扩展的 Person 实例列表,但 List(Of Person( 会将内容作为 Person 返回给您,而 arraylist 将它们作为对象返回,这需要转换为 Person

如果你想使这个正确面向对象,也许你应该在你的会话中放置一个购物车类的实例(你已经有一个继承页面的购物车,但我认为这个类是用来显示购物车内容的(。购物车可以有项目列表,跟踪优惠券,保持滚动总数等:

Class ShoppingCart
Public Property Items as List(Of ShoppingCartItem) 
Public Property Coupons as List(Of Coupon)
Public ReadOnly Property Total as Double
'Every time an item is added to items or coupons, recalc total
End Class
Class ShoppingCartItem
'Put properties here
End class

'And then in your page (rename it to ViewCart so it doesn't clash or put it in a different namespace)
Session("cart") = new ShoppingCart

你可能会惊呼"但与python相比,这是太多的工作!"——嗯,是的;这就是为什么.net语言被认为比脚本化、松散类型、相对更无规则的语言更成熟。您可以在 .net 中使用匿名类型,因此您不必正式声明类等,但声明对象/域层次结构并使用它具有价值,因为它使应用程序数据的建模更加严格,并迫使您更深入/深入地思考问题,而不仅仅是"我在这里需要一个额外的字符串 x, 我就把它扔在那里......"这就是当你使用一种"即时定义"的语言时得到的

最新更新