User987
User987

Reputation: 3823

Storing multiple values in Session under one key - possible list of Session

I'm trying to figure out a way to store multiple values in my Session variable. This is how I do it currently:

Session[ID] = Products;
Session["type"] = type;
Session["shipping"] = shipping;
Session["condition"] = condition;
Session["minprice"] = minprice;
Session["maxprice"] = maxprice;

The way I imagine it to be is that I store all these under the same KEY which is ID in my case ( an generated GUID value - 02df0-2k4l9 for example), so that I could access all of these values like following:

Session[ID]["type"];
Session[ID]["condition"];

And so on... Is there a way to do this, and if yes, what's the best possible way?

Upvotes: 2

Views: 3217

Answers (4)

Ghasan غسان
Ghasan غسان

Reputation: 5857

You can investigate what others have answered, including defining a specific class if that fits your requirements. In addition to what has been answered, you can use a dictionary that uses string as a key, and an object as a value. Then you can store in it your values, and read from it as the following.

var dictionary = new Dictionary<string, object>();

dictionary["type"] = type;
dictionary["shipping"] = shipping;
dictionary["condition"] = condition;
dictionary["minprice"] = minprice;
dictionary["maxprice"] = maxprice;

Session [ID] = dictionary;

Upvotes: 2

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

You can create a list of objects from your values lets assume you call it Product which is a class of your objects:

List<Product> list = new List<Product>();
//how to store them
Session["SessionName"] = list;
//how to receive the list again 
var list = (List<Product>)Session["SessionName"];

Upvotes: 1

Pranav Patel
Pranav Patel

Reputation: 1559

You can do like create a class which hold all the values

    public class ProductData
    {
        public Product objProduct { get; set; }
        public string type { get; set; }
        public string shipping { get; set; }
        public string condition { get; set; }
        public decimal minprice { get; set; }
        public decimal maxprice { get; set; }
    }

and assign that class object to session like

Session[ID] = objProductsData;

Upvotes: 1

Rohit Khanna
Rohit Khanna

Reputation: 723

How about creating a class MYCLASS with properties as "type", "shipping"... etc.. and store the instance of that class in session?

When you want to use it, simply Extract the instance from Session Variable , typecast it into MYCLASS and use it.

will that solve your problem ?

Cheers

Upvotes: 2

Related Questions