Before explaining code in detail let me give some knowledge power of HTTPSessionState class, since I have used Add/Remove method of HTTPSessionState class.
HTTPSessionState class Provides access to session-state values as well as session-level settings and lifetime management methods.
- Method -> Adds a new item to session state.
- Remove -> Delete an item from session state collection
There could be many method to make shopping cart.
- Fully database driven
- Collection based
Here I am discussing collection based shopping cart, question is why collection based?
Answer to this question is just to minimize load of the database from storing every activity of cart in the database.
Our aim is to hold product id and quantity in the collection, and while displaying the cart content list all the related data, based on product id from the table.
Updating Cart quantity in the cart is also in the collection which is achieved by using Javascript.
Note: On every link form is submitted using JavaScript and every action is maintained in ShoppingPage.aspx.vb in short Add To cart, Delete, Update etc.
In the entire shopping cart we have following pages:
- ShoppingPage.aspx and it's code behind page (Display product list).
- ShoppingCart.aspx and it's code behind page (Display cart content).
I will go through the major functionality on by one one each of above page
1. ShoppingPage.aspx
bindData()
Get the product list in SqlDataReader, it iterate through the product list and add rows to the table control, in one of the cell it has "Add To Cart" link.
<ahref='#'onclick=""javascript:document.Form1.action='ShoppingPage.aspx?Actn=Add&itemId=" & myRow.GetValue(0) & "';document.Form1.submit();"">Add To Cart</TD>"
In short submits form using javascript with Querystring Parameter Actn=Add and respective itemId from the row.
Since same page is acting as controlling page also, so each and every action is taken care on this page, let us have a look at "Add To Cart" functionality code snippet as below:
Private Sub AddToSession(ByVal strProduct As String, ByVal intQty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(Session(strProduct)) + intQty)
Else
Session.Add(strProduct, intQty)
End If
End Sub
Above code checks if the item is not present in the session, at first time it adds item id / product id with quantity 1 in the session, next time when same product / item is added to the cart it check if product id present if found update quantity + one.
Update Product
Private Sub updateCart(ByVal strProduct As String, ByVal qty As Integer)
If Not Session(strProduct) Is Nothing Then
Session.Add(strProduct, CInt(qty))
End If
End Sub
Above function is just to update cart product with quantity added in the textbox.
Delete Product
To remove product from the list, Remove() method of collection is used when Actn=Del & delItemId is passed from the querystring.
Session.Remove(delId)
The entire code for above all Action handling goes as below:
Dim strQty As Integer
Dim proId As String
Dim delId As String
delId = Request.QueryString("delItemId")
proId = Request.QueryString("itemId")
'---- Following portion act as controller where code is written as
'---- per the action from the request of the pages like Add To Cart,
'---- Update Cart & Delete Cart
strQty = 1
If Request.QueryString("Actn") <> "" Then
If Request.QueryString("Actn").Equals("Add") Then
If Request.QueryString("itemId") <> "" Then
AddToSession(proId, strQty)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Del") Then
If Request.QueryString("delItemId") <> "" Then
Session.Remove(delId)
Response.Redirect("./ShoppingCart.aspx")
End If
ElseIf Request.QueryString("Actn").Equals("Update") Then
If Request.QueryString("itemUpId") <> "" And Request.QueryString("quantity") <> "" Then
If IsNumeric(Request.QueryString("itemUpId")) Then
updateCart(Request.QueryString("itemUpId"), Request.QueryString("quantity"))
Response.Redirect("./ShoppingCart.aspx")
Else
Response.Redirect("./ShoppingCart.aspx")
End If
End If
End If
End If
Now we will have a look at ShoppingCart.aspx as below:
On this page I have following JavaScript function to take care of update function to which quantity and product Id / Item id parameters are supplied.
Function upThis(ByVal qty, ByVal upItemId)
{
var strUrl="./ShoppingPage.aspx?Actn=Update&quantity='+qty+'&itemUpId='+upItemId";
document.location.href = strUrl
}
On this page I have a table.
<
TABLE id="Table1" width="100%" align="center" borderColor="black" cellSpacing="0" cellPadding="1" border="1" runat="server">
where table Header row is generated with following heading:
- Product Name
- Quantity
- UnitPrice
- Amount
- Action
On this page we check Session.Count() and fetch product detail using following query:
SELECT * FROM products WHERE ProductId=" & Session.Keys(intI)
to Session.Keys(intI) we will be having item id / product id.
To above table with id="Table1" is added with dynamic row and each row has four cells.
The second row is added with some of the empty rows and Cart Total.
Entire code on this page goes as:
If
Not Page.IsPostBack Then
Dim intI As Integer
Dim strSql As String
Dim conn As New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
Dim cmd As SqlCommand
'Put user code to initialize the page here
Dim i As Integer
Dim j As Integer
Dim row As HtmlTableRow
Dim strTotal As Double = 0
For intI = 0 To Convert.ToInt16(Session.Count() - 1)
'Get the number of rows and columns selected by the user.
Dim numrows As Integer = Convert.ToInt16(Session.Count())
Dim numcells As Integer = 4
strSql = "SELECT * FROM products WHERE ProductId=" & Session.Keys(intI)
cmd = New SqlCommand(strSql, conn)
If conn.State = ConnectionState.Closed Then
conn.Open()
End If
showCart = cmd.ExecuteReader()
'Dim cell As HtmlTableCell
Dim cell1 As New HtmlTableCell
Dim cell2 As New HtmlTableCell
Dim cell3 As New HtmlTableCell
Dim cellAmount As New HtmlTableCell
Dim cellAction As New HtmlTableCell
If showCart.Read() Then
' Iterate through the rows.
' Create a new row and add it to the Rows collection.
row = New HtmlTableRow
' Provide a different background color for alternating rows.
If (intI Mod 2) = 1 Then
row.BgColor = "Gainsboro"
End If
' Iterate through the cells of a row.
cell1.Controls.Add(New LiteralControl(showCart.GetValue(1)))
cell2.Controls.Add(New LiteralControl("<input type='text' name=txt" & intI & " value=" & Session(intI)
& " maxlength='2' size='2'> <A href='#' onclick=""javascript:upThis(document.Form1.txt" & intI &
".value," & showCart.GetValue(0) & ");"">Update</A>"))
cell3.Controls.Add(New LiteralControl("$" & FormatNumber(showCart.GetValue(5), 0)))
cellAmount.Controls.Add(New LiteralControl("$" & FormatNumber(CDbl(showCart.GetValue(5)) *
CDbl (Session(intI)), 0)))
cellAction.Controls.Add(New LiteralControl("<a href='shoppingpage.aspx?Actn=Del&delItemId=" &
showCart.GetValue(0) & "'>Delete<A/>"))
row.Cells.Insert(0, cell1)
row.Cells.Insert(1, cell2)
row.Cells.Insert(2, cell3)
row.Cells.Insert(3, cellAmount)
row.Cells.Insert(4, cellAction)
Table1.Rows.Add(row)
' summing amount of all the products added in the cart content
strTotal = strTotal + FormatNumber(CDbl(showCart.GetValue(5)) * CDbl(Session(intI)), 0)
Else
'do nothing
End If
' closing recordset
showCart.Close()
Next
' cell declaratopm for adding rowTotal
Dim rowTotal As New HtmlTableRow
Dim cellEmpty1 As New HtmlTableCell
Dim cellEmpty2 As New HtmlTableCell
Dim cellEmpty3 As New HtmlTableCell
Dim celllTotalHeader As New HtmlTableCell
Dim cellTotal As New HtmlTableCell
'Creating seperate cell as literal controll
cellEmpty1.Controls.Add(New LiteralControl(" "))
cellEmpty2.Controls.Add(New LiteralControl(" "))
cellEmpty3.Controls.Add(New LiteralControl(" "))
celllTotalHeader.Controls.Add(New LiteralControl("Cart Total:$"))
cellTotal.Controls.Add(New LiteralControl(strTotal))
' Adding number of cells to the row
rowTotal.Cells.Insert(0, cellEmpty1)
rowTotal.Cells.Insert(1, cellEmpty2)
rowTotal.Cells.Insert(2, celllTotalHeader)
rowTotal.Cells.Insert(3, cellTotal)
rowTotal.Cells.Insert(4, cellEmpty3)
rowTotal.BgColor = "Gainsboro"
' Adding new row
Table1.Rows.Add(rowTotal)
End If
The above shoppingcart can be extended with one more intermediate stage as instead of having Add to cart functionality on first page we can product detail page to which product images/photos can be shown with more info and we can have "Add To Cart" functionality on the same page.
Another topic related with the shoppingcart to be discussed is: Payment Gateway.
One can add billing and shipping page with cart Total Amount and one can send to this information's to the payment gateways.
I have worked for code integration with following gateways:
- Authorized.net
- Verysign
- Worldpay
- YourPay
- Paypal
In next one of the session I will present code snippet for integrating with authorized.net payment gateway.