Click here to Skip to main content
15,909,466 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have stored multiple values in session using dictionary like below

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

                        get_values["name"] = model.Name; ;
                        get_values["address"] = model.Address;
                        get_values["phone"] = model.Phone;
                        get_values["email"] = model.Email;
                        

                        Session["sess_values"] = get_values;


now i want to get values from session one by one. my question is how to get values from session like name, address etc.?

What I have tried:

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

                        get_values["name"] = model.Name; ;
                        get_values["address"] = model.Address;
                        get_values["phone"] = model.Phone;
                        get_values["email"] = model.Email;
                        

                        Session["sess_values"] = get_values;
Posted
Updated 25-Aug-17 5:21am

Try:
C#
Dictionary<string, string> values = Session["sess_values"] as Dictionary<string, string>;
if (values != null)
   {
   string name = values["name"];
    ...
 
Share this answer
 
Comments
Richard Deeming 25-Aug-17 11:23am    
You'd need to change the definition of the value you stored in the session as well - from Dictionary<string, object> to Dictionary<string, string>.
OriginalGriff 25-Aug-17 11:41am    
True - I missed that.
Simple: retrieve the dictionary from the session; if it's not null, try to retrieve the value from the dictionary.
C#
var values = (Dictionary<string, object>)Session["sess_values"];
if (values != null)
{
    object value;
    if (values.TryGetValue("name", out value))
    {
        string s = value as string;
        if (s != null)
        {
            model.Name = s;
        }
    }
}

If you're using a recent version of Visual Studio, you can simplify that slightly:
C#
var values = (Dictionary<string, object>)Session["sess_values"];
if (values?.TryGetValue("name", out object value) && value is string s)
{
    model.Name = s;
}

But it's not obvious why you're using a Dictionary<TKey, TValue> in the first place, when you could just use the session directly:
C#
Session["name"] = model.Name;
model.Name = (string)Session["name"];
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900