views:

508

answers:

3

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?

+1  A: 

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.

Mehrdad Afshari
+2  A: 

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.

Joel Coehoorn
+2  A: 

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.

Matt Murrell
I was coding something very similar to this when I noticed a new answer to my question! Fortunately, our server has plenty of ram, low-usage, and it's not a large object. Thanks!
Ronnie Overby