简体   繁体   中英

Adding to a Session ASP.NET C#

I would like to add a Session["i"] with more results

currently it will only shows one set of results

eg School1 11/10/2011 14/11/2011 GCSE AAA

I would like to add more sets but they do not seem to be getting stored in the Session

eg

School1 11/10/2011 14/11/2011 GCSE AAA

School2 11/10/2012 14/11/2012 ALevels AAA

Education addResults = new Education(schoolName, fromDate, toDate , qualification , grades);

Session["i"] = (addResults );

//schoolarraylist.Add(addResults );

foreach (Education currentschool in schoolarraylist)
      {
         Session["i"] = currentschool.Schoollocation + "," + currentschool.Datefrom + "," + currentschool.Dateto + "," + currentschool.Qualifications + "," + currentschool.Grade + "<br />";

           string tmp = Session["i"].ToString();
           string[] sb = tmp.Split(',');
           string [] ii = new string[sb.GetUpperBound(0) + 1];

            for (int i = 0; i <= sb.GetUpperBound(0); i++)
                {
                    ib[i] = (sb[i]);
                }

            foreach (string j in ii)
                {
                    Response.Write(ii);
                }

            }

You can assign list of object to session and later get it back. But you should not put data in seesion without need . Session are maintained on server side for each user and putting data in session takes memory of server and it is could degrade the performance of the application. Its worth reading about sessions before using them.

List<string> lst = new List<string>();

Session["i"] = lst;

Getting list back from session object.

List<string> lst = (List<string>)Session["i"];

The Problem is, that you assign something to Session["i"] and when you try to add something to the session, you actually overwrite your previous value. In order to add objects to the Session, you either have to chose another name eg Session["j"] or wrap some sort of container around your objects (List, Array, Dictionary, etc.) and store that container in your Session.

Also try to find better names for your Sessions, if you take a look at your code at a later point, you probably won't know what Session["i"] is actually supposed to be.

You can also use a ArrayList :

ArrayList list = new ArrayList();
foreach (Education currentschool in schoolarraylist)
{
    list.Add(currentschool.Schoollocation + "," + currentschool.Datefrom + "," + currentschool.Dateto + "," + currentschool.Qualifications + "," + currentschool.Grade)
}

Then loop through the arraylist and display in whatecver format you want to display

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