Tutorial :ASP.NET Server Side Viewstate



Question:

I have read some approaches to storing viewstate on the server:

Here is one

Here is another

But they are sort of complicated. I am looking for a way to persist an object without having to serialize it. I could use session state, but if a user opens more than one window, there could be overwrites of the object.

Is there a simple solution to this?


Solution:1

In this situation I would put store the object in the session using a unique key and tie the key to the page. All this can be abstracted into properties on the page class.

public string PersistanceKey  {      get {           if(ViewState["PersistanceKey"] == null)             ViewState["PersistanceKey"] = "Object" + Guid.NewGuid().ToString();            return (string)ViewState["PersistanceKey"];      }  }    public PersistanceObject Persistance  {      get {          if(Session[this.PersistanceKey] == null)              Session[this.PersistanceKey] = new PersistanceObject();            return (PersistanceObject)Session[this.PersistanceKey];  }  

The different session keys would allow different objects on a per-page basis. Alternately, instead of using the Session object, you could consider using the application cache (the Cache object) to automatically remove stale entries out of memory, but this has its own caveats.

It should be noted that Joel's warnings on his answer about memory usage are entirely accurate. This might not be the best idea for low-memory, high-usage, or large-persistance-object scenarios.


Solution:2

I am looking for a way to persist an object without having to serialize it.

Be careful with that. This will have a dramatic impact on the memory use of your site, and memory use is often the biggest impediment to scalability.


Solution:3

Assign a number to each window the user might open. Append that number to the session key. You should also store the number somewhere in page (querystring or a hidden input) to be able to retrieve the appropriate session variable.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »