Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Web Development
  3. ASP.NET
  4. Adding Objects To Session

Adding Objects To Session

Scheduled Pinned Locked Moved ASP.NET
help
9 Posts 5 Posters 1 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    ASPnoob
    wrote on last edited by
    #1

    I have a list called List < Accounts > where I can add customers' info after supplying the needed data and clicking the Add button on my webform. To persist my data between postbacks I stored my data in a session variable then retrieve them from that session variable later on. The problem is the session variable only shows one account even though I added multiple accounts. The folloewng is my code.

    List accts = new List();

    protected void btnShowAccountDetails_Click(object sender, EventArgs e)
    {
    StringBuilder acctDetails = new StringBuilder();

    if (Session\["acctObjects"\] != null)
    accts = (List)Session\["acctObjects"\];
    
    foreach(Account acct in accts)
    {
     acctDetails.Append("ID: "+ acct.Name + " Account ID: " + acct.AccountID + "<br/>");
    }   
    
    litCtrShowAccountDetails.Text = acctDetails.ToString();
    

    }

    protected void btnAddAcctount_Click(object sender, EventArgs e)
    {
    Account acct = new Account();
    StringBuilder acctDetails = new StringBuilder();

    if (!String.IsNullOrEmpty(txtName.Text))
    {
    acct.Name = txtName.Text;	
    }
    else
    {
    //Display Error message
    ScriptManager.RegisterStartupScript(this, GetType(), "EmptyName", "EmptyNameAlert();", true);
    }
    
    if (!String.IsNullOrEmpty(txtAccountID.Text))
    {
    acct.AccountID = txtAccountID.Text;	
    }
    else
    {
    //Display Error message
    ScriptManager.RegisterStartupScript(this, GetType(), "EmptytAccountID", "EmptytAccountIDAlert();", true);
    }
    
    accts.Add(acct);
    Session\["acctObjects"\] = accts;
    

    }

    Please help me resolve this issue, thanks in advance.

    Z M 2 Replies Last reply
    0
    • A ASPnoob

      I have a list called List < Accounts > where I can add customers' info after supplying the needed data and clicking the Add button on my webform. To persist my data between postbacks I stored my data in a session variable then retrieve them from that session variable later on. The problem is the session variable only shows one account even though I added multiple accounts. The folloewng is my code.

      List accts = new List();

      protected void btnShowAccountDetails_Click(object sender, EventArgs e)
      {
      StringBuilder acctDetails = new StringBuilder();

      if (Session\["acctObjects"\] != null)
      accts = (List)Session\["acctObjects"\];
      
      foreach(Account acct in accts)
      {
       acctDetails.Append("ID: "+ acct.Name + " Account ID: " + acct.AccountID + "<br/>");
      }   
      
      litCtrShowAccountDetails.Text = acctDetails.ToString();
      

      }

      protected void btnAddAcctount_Click(object sender, EventArgs e)
      {
      Account acct = new Account();
      StringBuilder acctDetails = new StringBuilder();

      if (!String.IsNullOrEmpty(txtName.Text))
      {
      acct.Name = txtName.Text;	
      }
      else
      {
      //Display Error message
      ScriptManager.RegisterStartupScript(this, GetType(), "EmptyName", "EmptyNameAlert();", true);
      }
      
      if (!String.IsNullOrEmpty(txtAccountID.Text))
      {
      acct.AccountID = txtAccountID.Text;	
      }
      else
      {
      //Display Error message
      ScriptManager.RegisterStartupScript(this, GetType(), "EmptytAccountID", "EmptytAccountIDAlert();", true);
      }
      
      accts.Add(acct);
      Session\["acctObjects"\] = accts;
      

      }

      Please help me resolve this issue, thanks in advance.

      Z Offline
      Z Offline
      ZurdoDev
      wrote on last edited by
      #2

      You instantiate accts as a new List of Accounts. Then all you do is add 1 account when the button is clicked. So, when you click the button again, the variable is accts is being set as new again.

      There are only 10 types of people in the world, those who understand binary and those who don't.

      1 Reply Last reply
      0
      • A ASPnoob

        I have a list called List < Accounts > where I can add customers' info after supplying the needed data and clicking the Add button on my webform. To persist my data between postbacks I stored my data in a session variable then retrieve them from that session variable later on. The problem is the session variable only shows one account even though I added multiple accounts. The folloewng is my code.

        List accts = new List();

        protected void btnShowAccountDetails_Click(object sender, EventArgs e)
        {
        StringBuilder acctDetails = new StringBuilder();

        if (Session\["acctObjects"\] != null)
        accts = (List)Session\["acctObjects"\];
        
        foreach(Account acct in accts)
        {
         acctDetails.Append("ID: "+ acct.Name + " Account ID: " + acct.AccountID + "<br/>");
        }   
        
        litCtrShowAccountDetails.Text = acctDetails.ToString();
        

        }

        protected void btnAddAcctount_Click(object sender, EventArgs e)
        {
        Account acct = new Account();
        StringBuilder acctDetails = new StringBuilder();

        if (!String.IsNullOrEmpty(txtName.Text))
        {
        acct.Name = txtName.Text;	
        }
        else
        {
        //Display Error message
        ScriptManager.RegisterStartupScript(this, GetType(), "EmptyName", "EmptyNameAlert();", true);
        }
        
        if (!String.IsNullOrEmpty(txtAccountID.Text))
        {
        acct.AccountID = txtAccountID.Text;	
        }
        else
        {
        //Display Error message
        ScriptManager.RegisterStartupScript(this, GetType(), "EmptytAccountID", "EmptytAccountIDAlert();", true);
        }
        
        accts.Add(acct);
        Session\["acctObjects"\] = accts;
        

        }

        Please help me resolve this issue, thanks in advance.

        M Offline
        M Offline
        Mathi Mani
        wrote on last edited by
        #3

        The issue is where you add the accts which is a List<Account> to the session. These two lines of code always replace whatever object present in Session["acctObjects"]

        accts.Add(acct);
        Session["acctObjects"] = accts;

        To avoid the overwrite, whenever you want to add a Account to List<Account> stored in session, get the List from session, add new Account to that list and store it back to session. Here is how you can do it.

        if (Session["acctObjects"] != null)
        accts = (List<acct>)Session["acctObjects"];
        accts.Add(acct);
        Session["acctObjects"] = accts;

        A F 2 Replies Last reply
        0
        • M Mathi Mani

          The issue is where you add the accts which is a List<Account> to the session. These two lines of code always replace whatever object present in Session["acctObjects"]

          accts.Add(acct);
          Session["acctObjects"] = accts;

          To avoid the overwrite, whenever you want to add a Account to List<Account> stored in session, get the List from session, add new Account to that list and store it back to session. Here is how you can do it.

          if (Session["acctObjects"] != null)
          accts = (List<acct>)Session["acctObjects"];
          accts.Add(acct);
          Session["acctObjects"] = accts;

          A Offline
          A Offline
          ASPnoob
          wrote on last edited by
          #4

          Thanks for replying your suggestion is very helpful.

          1 Reply Last reply
          0
          • M Mathi Mani

            The issue is where you add the accts which is a List<Account> to the session. These two lines of code always replace whatever object present in Session["acctObjects"]

            accts.Add(acct);
            Session["acctObjects"] = accts;

            To avoid the overwrite, whenever you want to add a Account to List<Account> stored in session, get the List from session, add new Account to that list and store it back to session. Here is how you can do it.

            if (Session["acctObjects"] != null)
            accts = (List<acct>)Session["acctObjects"];
            accts.Add(acct);
            Session["acctObjects"] = accts;

            F Offline
            F Offline
            F ES Sitecore
            wrote on last edited by
            #5

            Slightly pedantic but to avoid your code throwing an error when the session times out I'd code this more defensively

            if (Session["acctObjects"] != null)
            accts = (List<acct>)Session["acctObjects"];
            else
            accts = new List<acct>();

            accts.Add(acct);
            Session["acctObjects"] = accts;

            Richard DeemingR 1 Reply Last reply
            0
            • F F ES Sitecore

              Slightly pedantic but to avoid your code throwing an error when the session times out I'd code this more defensively

              if (Session["acctObjects"] != null)
              accts = (List<acct>)Session["acctObjects"];
              else
              accts = new List<acct>();

              accts.Add(acct);
              Session["acctObjects"] = accts;

              Richard DeemingR Offline
              Richard DeemingR Offline
              Richard Deeming
              wrote on last edited by
              #6

              Alternatively:

              const string AcctObjectsSessionKey = "acctObjects";
              ...
              accts = (List<acct>)Session[AcctObjectsSessionKey] ?? new List<acct>();
              accts.Add(acct);
              Session[AcctObjectsSessionKey] = accts;

              That avoids the possibility of the session object being removed between the existence check and the retrieval. :)


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              F 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                Alternatively:

                const string AcctObjectsSessionKey = "acctObjects";
                ...
                accts = (List<acct>)Session[AcctObjectsSessionKey] ?? new List<acct>();
                accts.Add(acct);
                Session[AcctObjectsSessionKey] = accts;

                That avoids the possibility of the session object being removed between the existence check and the retrieval. :)


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                F Offline
                F Offline
                F ES Sitecore
                wrote on last edited by
                #7

                Fair point, not sure if that is possible though.

                Richard DeemingR 1 Reply Last reply
                0
                • F F ES Sitecore

                  Fair point, not sure if that is possible though.

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #8

                  I've seen too many bugs caused by "impossible" events to take the risk. :-D


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  F 1 Reply Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    I've seen too many bugs caused by "impossible" events to take the risk. :-D


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    F Offline
                    F Offline
                    F ES Sitecore
                    wrote on last edited by
                    #9

                    I agree, which is why I'd use "as" rather than casting as you did in your example as your code would error if the session variable existed but contained a different object ;P Sessions last for the period of the page execution. It has to exist for the page to start executing so can't time-out mid execution. It'll only become unavailable if something terminal has happened like the app unloading, and your code will stop working in that instance anyway.

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups