tags:

views:

93

answers:

3

Hi guys,

Is there a way to add List in session? or any other way to pass the values of List in another page?

+2  A: 

You can do these kinds of things, if this is what you are asking.

Session["key"] = List<string>;

as well as

myStrings = (List<string>)Session["key"];
jarrett
Session["key"] as List<string> is better. And remember to check if it's null before convertion.
Danny Chen
+6  A: 
List<string> ast = new List<string>();
        ast.Add("asdas!");
        Session["stringList"] = ast;
        List<string> bst = (List<string>)Session["stringList"];
Chinjoo
A: 

You may want to explore the following two extensions method for HttpSessionState class.

    public static System.Nullable<T> GetValue<T>(this HttpSessionState session, string key) where T : struct, IConvertible
    {
        object value = session[key];
        if (value != null && value is T)
        {
            return (T)value;
        }
        else
            return null;
    }


    public static T GetValue<T>(this HttpSessionState session, string key, T defaultValue) where T : class
    {
        object value = session[key] ?? defaultValue;
        if (value != null && value is T)
        {
            return (T)value;
        }
        else
            return default(T);
    }

The former is for value type and the latter is for reference type.

The usage is as follows:

   int? _customerId = Session.GetValue<int>("CustomerID");
   Customer _customer = Session.GetValue<Customer>("CurrentCustomer", null);
Kthurein