我正在使用ASP和VB.net建立一个网站(我有一个存储在其中的所有产品的mysql数据库),我需要创建一个添加到购物车按钮,以便稍后在购物车中显示它。
为此,我决定将数据库中的项目ID存储到会话变量中,并在购物车页面上将其检索回来,以显示有关该产品的其他信息。但每次用户点击按钮将项目添加到购物车时,我都需要向会话数组添加一个新变量。但我无法弄清楚每次点击时如何向数组添加变量。
Private _cmd As MySqlCommand
Private _adapter As MySqlDataAdapter
Dim myCookie As HttpCookie = New HttpCookie("Cart")
Dim item As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
ViewProduct()
End Sub
Private Sub ViewProduct()
Dim Cart(10) As String
Dim QueryStr As String
_conn = New MySqlConnection
_conn.ConnectionString = ConfigurationManager.ConnectionStrings("ProductConn").ConnectionString
Dim _reader As MySqlDataReader
_conn.Open()
QueryStr = "SELECT * FROM products.items "
_cmd = New MySqlCommand(QueryStr, _conn)
_reader = _cmd.ExecuteReader()
For index As Integer = 0 To 48 Step 1
_reader.Read()
If Request.RawUrl = "/ZTY_Fashion/Scripts/Viewproduct.aspx?id=" + _reader("productID").ToString Then
ImageButton1.ImageUrl = _reader("productImg").ToString
name.Text = _reader("productName").ToString
product.Text = _reader("productDisc").ToString
price.Text = _reader("productPrice").ToString
addtocart.Text = "Buy Now"
quantity.Text = "Quantity in stock" + " " + _reader("Instock").ToString
quantitytxt.Text = "Quantity"
similar.Text = "Similar Items in stock"
ID.Text = _reader("productID").ToString
End If
Next index
_reader.Close()
Dim rnd = New Random()
Dim nextValue = rnd.Next(48) / 1
QueryStr = "SELECT * FROM products.items WHERE productID='" & nextValue & "'"
_cmd = New MySqlCommand(QueryStr, _conn)
_reader = _cmd.ExecuteReader()
For i As Integer = 0 To 48 Step 1
_reader.Read()
Select Case i
Case 0
imgdisplay.ImageUrl = _reader("productImg").ToString
End Select
Next i
_reader.Close()
_conn.Close()
End Sub
Protected Sub addtocart_Click(sender As Object, e As EventArgs) Handles Button20.Click
//This is where i would like to add the code
End Sub
End Class
答案 0 :(得分:0)
您可以在会话中存储自己的自定义对象列表,然后只需将这些对象的集合存储在会话中,例如List<CustomerCartItem>
。将其转换为VB.net,因为它在c#
创建一个类
public class CustomerCartItem
{
// add what you need here, if you dont need quantity or name, just remove
// both, and only take Product ID
public int ProductID {get;set;}
public int Quantity {get;set;}
public int Name {get;set;}
}
当您要在购物车中添加新产品时
if(Session["customerCartItem"] != null){
List<CustomerCartItem> items = (List<CustomerCartItem>)Session["customerCartItem"];
items.Add(new CustomerCartItem() { ProductID = 1, Quantity = 2, Name = 'Prod1' })
Session["customerCartItem"] = items ;
}
else
{
List<CustomerCartItem> items = new List<CustomerCartItem>();
items.Add(new CustomerCartItem() { ProductID = 1, Quantity = 2, Name = 'Prod2' })
Session["customerCartItem"] = items ;
}