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.
 
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...
 
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'
 
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