简体   繁体   中英

Store multiple values in a session variable

Before I ask my question, please consider this scenario: a user on my website has a profileID . There are some pluginID 's associated with this profileID .

Eg: User1 might have 2, 3 and 5 plugins associated with his profile.

When the user logs in, I store the profileID of the user in a session variable cod . ON a certain page, the user tries to edit the plugins associated with his profile. So, on that page, I have to retrieve those pluginID 's from the DB.

I have applied this code but this fetches only the maximum pluginID from the DB and not all the pluginID 's.

SqlCommand cmd1 = new SqlCommand("select plugin_id from profiles_plugins where id=(select id from profiles_plugins where profile_id=" + Convert.ToInt32(Session["cod"]) + ")", con);
SqlDataReader dr1 = cmd1.ExecuteReader();
if (dr1.HasRows)
{
  while (dr1.Read())
  {
    Session["edp1"] = Convert.ToInt32(dr1[0]);
  }
}
dr1.Close();
cmd1.Dispose();

I was trying to figure out how can I store multiple pluginID 's in this session variable?

Thanks

Read the value to a list or array first and then store the list or array:

using(SqlCommand cmd1 = new SqlCommand("select plugin_id from profiles_plugins where id=(select id from profiles_plugins where profile_id=" + Convert.ToInt32(Session["cod"]) + ")", con))
{

    SqlDataReader dr1 = cmd1.ExecuteReader();
    var yourList = new List<int>();
    if (dr1.HasRows)
    {
        while (dr1.Read())
        {
           yourList.Add(Convert.ToInt32(dr1[0]));
        }
    }
    Session["edp1"] = yourList;
    dr1.Close();
}

Also, read Marc Gravell's comment on your question.

You can store whatever objects you like under a session key, not only scalar values. So simply define a custom type containing all the values you would like to store, create an instance of this type and put it into the session.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM