[英]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.