How to save an array of objects in C # ASP.Net Sesssion?

My C # ASP.Net program has an array of objects that populate during the postback, and I want to restore them during the next postback. To this end, I include the declaration of the array in the definition of the Default class, which is saved this way: -

this.Session["This"] = this; 

and restored: -

 Default saved_stuff = (Default) this.Session["This"]; 

This works great for everything except: -

 MyClass [] my_array; 

When restored, saved_stuff.my_array always null .

MyClass is defined as follows: -

 public MyClass : ISerializable { private string some_string; private double some_double; // some more simple members // Some getters and setters // ISerializable Implementation } 

I tried to make MyClass implementation of ISerializable , but that doesn't make any difference. Does anyone know what I should do?

Edit to answer @Michael's question, then I do things like ...

 for (int i = 0; i <= saved_stuff.my_array.GetUpperBound(0); i++) { // blah blah } 

which fails with "object reference not set to object instance". All other Default member variables are displayed in saved_stuff when debugging.

+4
source share
3 answers

You need to save the array data in your own session object:

 MyClass[] my_array = //Something Session["ArrayData"] = my_array; 

Then extract it as:

 var arrayData = (MyClass[])Session["ArrayData"]; 
+6
source

According to MSDN , if you store the session state in memory (default), then it does not need to be serialized

When you use a session state mode other than InProc , the type of the session variable must be either a primitive .NET type or serializable. This is because the value of the session variable is stored in an external data store.

I suspect something else is clearing the array. remember, that

 this.Session["This"] = this; 

when using session state, a copy of your page object is not created in memory, so any changes you make to the page object (" this ") will also be made to the "saved" object. Therefore, if you set this._saved_stuff = null , then the property of the saved object will also be null.

I would not try to save the page in a session, but select and choose which values ​​you want to save and save them explicitly.

Alternatively, if you want the values ​​to be restored in the next postback, you can choose ViewState instead. Using Session does pose some risk that the session will be destroyed between postbacks. It may be rare, but it is a question.

+3
source

First of all, you should know that in Asp.net web application there are three types of session state 1. in process 2. State server 3. In the database

you can save the object directly in the session if the state of the session is in process (which is defalut), or you need to note that your object will be serializable, which will allow you to save the object on the state server or in the database (installed in the configuration file)

+1
source

All Articles