ASP.NET Session Shopping Cart Items issue on pageload not updating
I.e. I have a piece of code on my page as follows, which is in page_load
Dim subTotal As Integer = 0
For Each item As CartItem In ShoppingCart.Instance.Items
subTotal += 1
Next
strShoppingCart.Append(subTotal).Append(" Items")
shoppingCartItems.Text = strShoppingCart.ToString()
And I can then add items to my cart as follows
Protected Sub Update_Click(ByVal sender As Object, ByVal e As EventArgs) Dim rowscount As Integer = productListTable.Rows.Count
For Each row As GridViewRow In productListTable.Rows
If row.RowType = DataControlRowType.DataRow Then
' We'll use a try cat开发者_开发技巧ch block in case something other than a number is typed in. If so, we'll just ignore it.
Try
' Get the productId from the GridView's datakeys
Dim productId = Convert.ToInt32(productListTable.DataKeys(row.RowIndex).Value)
' Find the quantity TextBox and retrieve the value
Dim quantity = Integer.Parse(CType(row.Cells(1).FindControl("txtQuantity"), TextBox).Text)
'Dim price = Decimal.Parse(CType(row.Cells(1).FindControl("TradePriceField"), Label).Text)
Dim price = Decimal.Parse("16.00")
Dim productName = CType(row.Cells(1).FindControl("ProductNameField"), Label).Text
Dim packSize = Integer.Parse(CType(row.Cells(1).FindControl("PackSizeField"), Label).Text)
Dim stockIndicator = Integer.Parse(CType(row.Cells(1).FindControl("PackSizeField"), Label).Text)
ShoppingCart.Instance.AddItem(productId, quantity, price, productName, packSize, stockIndicator)
Catch ex As FormatException
End Try
End If
Next
End Sub
The problem is as follows
Page Load Items Count is 0
I add a product the page still says 0 Items when there is actually 1 item in session I refresh the page the counter goes to one
How can I to read from correct session count ?
Page_Load
is going to fire before Update_Click
, which is why you're not seeing the count increase after the initial form submit. You'll need to either update the shoppingCartItems
control after Update_Click
executes, or you can Response.Redirect
back to the page to get the display to update. I personally like to use Response.Redirect
after a post because if the user refreshes the page then you won't see that browser message that says it is going to repost the data.
You also might want to check out the ASP.NET Page Life Cycle.
I had a similar problem with a shopping cart, but I used AJAX updatepanels and the Redirect did not work the AJAX way.
I used mycartlistview.DataBind()
in my code after an item was added to the shopping cart.
精彩评论