c#.Net storing session 'arrays'

Associate
Joined
17 Mar 2008
Posts
135
Say if I want to pass a query via link (default.aspx?id=1&qty=10), and then store it in a session so that it can be retrieved in a 'basket' for later processing, how would I go about storing sessions in a array. There could possibly be up to 20 products, and I will need to store a product id and quantity both passed via an url.


Code:
session["basketitems"] = Request.Querystring["id];

How would I add a so that there individually stored.

Any help appreciated.
 
add the values to a dataset and store the dataset in session?

to add bring the ds out of session then add your item then wack it all back into session and vice versa.
 
Something like this might do the trick, or at least point you in the right direction. Essentially each item in the basket is respresented by a csv string comprised of the id and quantity, then stored in a collection of such strings within session state.

Code:
[FONT=Courier New][COLOR=lime]// Create the collection in the session[/COLOR][/FONT]
[FONT=Courier New][COLOR=royalblue]ICollection[/COLOR]<[COLOR=royalblue]string[/COLOR]> basketitems = new [COLOR=royalblue]List[/COLOR]<[COLOR=royalblue]string[/COLOR]>();[/FONT]
[FONT=Courier New]Session["basketitems"] = basketitems;[/FONT]
Code:
[FONT=Courier New][COLOR=lime]// Add an item to the collection[/COLOR][/FONT]
[FONT=Courier New][COLOR=royalblue]ICollection[/COLOR]<[COLOR=royalblue]string[/COLOR]> basketitems = Session["basketitems"] as [COLOR=royalblue]ICollection[/COLOR]<[COLOR=royalblue]string[/COLOR]>;[/FONT]
[FONT=Courier New]basketitems.Add([COLOR=royalblue]string[/COLOR].Format("{0},{1}", Request.QueryString["id"], Request.QueryString["qty"]));[/FONT]
Code:
[FONT=Courier New][COLOR=lime]// Iterate over the collection[/COLOR][/FONT]
[FONT=Courier New][COLOR=royalblue]ICollection[/COLOR]<[COLOR=royalblue]string[/COLOR]> basketitems = Session["basketitems"] as [COLOR=royalblue]ICollection[/COLOR]<[COLOR=royalblue]string[/COLOR]>;[/FONT]
[FONT=Courier New][COLOR=royalblue]foreach[/COLOR] ([COLOR=royalblue]string[/COLOR] basketitem [COLOR=royalblue]in[/COLOR] basketitems)[/FONT]
[FONT=Courier New]{[/FONT]
[FONT=Courier New][COLOR=royalblue]    string[/COLOR][] parts = basketitem.Split(',');[/FONT]
[FONT=Courier New][COLOR=royalblue]    int[/COLOR] id = [COLOR=royalblue]int[/COLOR].Parse(parts[0]);[/FONT]
[FONT=Courier New][COLOR=royalblue]    int[/COLOR] qty = [COLOR=royalblue]int[/COLOR].Parse(parts[1]);[/FONT]
[FONT=Courier New]}[/FONT]

You could expand on this by creating a simple object to represent each item in the basket, and then store a collection of these objects instead.
 
Last edited:
I would create a 'Basket' class to hold everything for the basket then just store this object in the session when needed.
 
No problem, and as Gman said you could take the example even further and create a Basket class to act as a container for BasketItem objects, rather than the generic collection I used in my example. Just remember to apply the Serializable attribute to any custom class that you want to store in session state.
 
Ok so I got a working version, so for anyone interested I'm using the following code in the 'page behind'

Code:
protected void Page_Load(object sender, EventArgs e)
    {

        if (Session["basketnew"] != "false")
        {
            // Create the collection in the session
            ICollection<string> basketitems = new List<string>();
            Session["basketitems"] = basketitems;

        }
        


        if (Request.QueryString["id"] == null || Request.QueryString["id"].Length == 0)
        {

        }
        else
        {
            // Add an item to the collection
            ICollection<string> basketitems = Session["basketitems"] as ICollection<string>;
            basketitems.Add(string.Format("{0},{1}", Request.QueryString["id"], Request.QueryString["qty"]));

            Session["basketnew"] = "false";
        }

        // Iterate over the collection
        ICollection<string> basketitemss = Session["basketitems"] as ICollection<string>;
        foreach (string basketitem in basketitemss)
        {
            string[] parts = basketitem.Split(',');
            int id = int.Parse(parts[0]);
            int qty = int.Parse(parts[1]);
            // Response.Write(id);
            //Response.Write(qty);
        }
       
    }

This is activated by sending a link with an id and qty query, e.g.

link.aspx?id=10&qty=9

Seems to do the job just fine, hopefully I haven't made some silly obvious mistake.

Thanks again to all that helped :D
 
Infact! following on from this notion:

What would be best practice if you were to return to a page and click 'add product to basket' for a second time, as the code above would add it as an individual node, as opposed to taking the id and adding the two 'quantities' together.

For now the site I'm designing will be fine with the above, but maybe for future developments it might be worth while having a 'temp table' to store these details...

Any thoughts welcomed...
 
You could achieve this by storing a dictionary of basketitems, rather than a collection. Something like this perhaps...

Code:
// Create the basket
 
IDictionary<int, int> basket = new Dictionary<int, int>();
Session["basket"] = basket;
Code:
// Add items the basket
 
IDictionary<int, int> basket = Session["basket"] as IDictionary<int, int>;
 
int itemID = int.Parse(Request["id"]);
int itemQuantity = int.Parse(Request["qty"]);
 
// Determine if the item already exists in our basket
int existingQuantity;
 
if (basket.TryGetValue(itemID, out existingQuantity))
{
    // Add the new quantity to the existing quantity.
    basket[itemID] = existingQuantity + itemQuantity;
}
else
{
    // Add the new item to the basket.
    basket[itemID] = itemQuantity;
}

Again the dictionary could be replaced with a Basket class if you wanted to explore that route.
 
Last edited:
Mate you must bleed c#! i'm well impressed, thanks :D

Quick question, what would be the best way to 'echo' these results (I come from a php so maybe going at it the wrong way).

But i'm unable to do a 'foreach' loop on the session array... I'm getting an error on the 'icollection'
 
Quick question, what would be the best way to 'echo' these results (I come from a php so maybe going at it the wrong way).
To write the values to the page you could use Reponse.Write(...) or perhaps write to a control on your page. You could also look at using
System.Diagnostics.Debug.WriteLine(...) to output to the Visual Studio "output" window.

But i'm unable to do a 'foreach' loop on the session array... I'm getting an error on the 'icollection'

You'll need to iterate over the Keys collection on the dictionary...

Code:
foreach (int itemID in basket.Keys)
{
    int itemQuantity = basket[itemID];
}
 
Wicked, that's where I was going wrong, I was trying to loop on the session name.

Will give that a crack, thanks a bunch for all your help.:)
 
Back
Top Bottom