繁体   English   中英

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

[英]how to create Session object/dictionary in 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

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

'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 中显示 Session 购物车。

An arraylist is not a dictionary, so by storing an arraylist in the Session you're limiting yourself to working with an arraylist. 您至少可以将 ShoppingCartItems 存储在 arraylist 中,然后您就可以访问它们并为其编制索引。

Arraylist 已经很老了,自从通用 collections 出现以来,我就不再使用它了。 我看不出 ArrayList 有任何用处,例如一个 List(Of Person) - 两者都将存储一个扩展的 Person 实例列表,但 List(Of Person) 会将事情作为一个人返回给你,而 arraylist 返回它们作为对象,这需要强制转换为 Person

If you want to make this properly object oriented perhaps you should put an instance of a shopping cart class (you already have a shopping cart that inherits page but I'm hence thinking that this class is for showing the shopping cart contents) in your session . 购物车可以有一个项目列表,跟踪优惠券,保持滚动总数等:

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 在这里。我会把它扔在那里..”这就是您使用一种语言时所得到的事情是“动态定义的”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM