HOME      WEB DEVELOPMENT      WEB DESIGN      PORTFOLIO      BLOG      ABOUT JS      CONTACT JS







Archive for the ‘Shopping Carts’ Category

.NET Shopping Cart Example Using Only Session Variables

Friday, November 21st, 2008


Shopping carts are basically a dime a dozen.  But there’s always some component of them that doesn’t quite fit into your current model.  So what do you do when you are up against a deadline and need to quickly produce a basic front end of a shopping cart to hold items and quantities in .NET using on Session Variables?

I came up with this solution after thinking about a quick way to avoid having to read and write to a database, but not storing elaborate arrays and such to try and accomplish a very simple shopping cart structure.


// Get the Item We're Going to Add to the Cart
int itemID = Convert.ToInt32(Request.QueryString["itemid"]);

// Get the Item (I use a Business Logic here, but you could easily grab the item information from your //database call or items from a grid, etc.
item m = new item();
itemAssembler ma = new itemAssembler();
m = ma.ReadSingleByKey(itemID);

// Now grab a random number so we can track the items in the cart individually

Random rand = new Random();
int x;
x = rand.Next(100000, 999999);

// Check and see....Do we have a cart already?
if (Session["cart"] == null)
{

// Add the item to the cart
NameValueConfigurationCollection cart = new NameValueConfigurationCollection();

//Add an Item to the cart ("ITEM",Variance, ItemID,Quantity)
NameValueConfigurationElement nvc = new NameValueConfigurationElement("ITEM," + x.ToString() + "," + "1", m.id.ToString());
cart.Add(nvc);
Session["cart"] = cart;
}
else
{
NameValueConfigurationCollection cart = Session["cart"] as NameValueConfigurationCollection;

//Add an Item to the cart ("ITEM",ItemID,Quantity)
NameValueConfigurationElement nvc2 = new NameValueConfigurationElement("ITEM," + x.ToString() + "," + "1", m.id.ToString());
cart.Add(nvc2);
Session["cart"] = cart;
}

// Now take your user to the cart view page you'd create
Response.Redirect("your_cart.aspx");

Now on our “your_cart” page, you can now loop through the items in the cart and display them however you’d like.


// Let's load the items from the shopping cart into the table
NameValueConfigurationCollection cart = Session["cart"] as NameValueConfigurationCollection;
foreach (NameValueConfigurationElement n in cart)
{

//Now split the value for the Item Type, the ID, and the Quantity
String typelist = n.Name;
char[] sep = { ' ', ',', '.', ':', '\t' };
String[] typeitems = typelist.Split(sep);

//Hold these values in some String Variables
String type = typeitems[0];
String cartitem = typeitems[1];
String qty = typeitems[2];

//Now set up our currency display
System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
nfi.CurrencyDecimalDigits = 2;
nfi.CurrencySymbol = "$";

//Take your business/data logic and grab the information
item i = new item();
itemAssembler ia = new itemAssembler();
itemCriteria ic = new itemCriteria();

if(ia.ReadSingleByKey(Convert.ToInt32(n.Value)) != null)
{
i = ia.ReadSingleByKey(Convert.ToInt32(n.Value));

// Get the Retail Price
int productid = i.id;
pricing pps = new pricing();
decimal retailprices = Convert.ToDecimal(i.retail);// +Convert.ToDecimal(i.shipping);

//Now take the Table you have on your display page and add rows to it...
HtmlTableRow mainrow = new HtmlTableRow();
HtmlTableCell maincell = new HtmlTableCell();
maincell.InnerHtml = "
" + i.name + " Remove Item

";
mainrow.Cells.Add(maincell);
tblCase.Rows.Add(mainrow);

}

System.Globalization.NumberFormatInfo tnfi = new System.Globalization.NumberFormatInfo();
tnfi.CurrencyDecimalDigits = 2;
tnfi.CurrencySymbol = "$";

// Now populate the items on the Total Costs Table
lblSubtotal.Text = String.Format(tnfi, "{0:c}", subtotal);
lblTax.Text = String.Format(tnfi, "{0:c}", tax);
lblShipping.Text = String.Format(tnfi, "{0:c}", shipping);
total = subtotal + shipping + tax;
lblTotal.Text = String.Format(tnfi, "{0:c}", total);
}

You now have a simple shopping cart in just a few lines of code since most of the code is used to get the information about your particular item and can be streamlined even more if you wanted to store all of that into the string as well. Ok, so now that you have a way to put together a quick cart for your client before morning….happy coding