Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Server Side Viewstate

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?

like image 957
Ronnie Overby Avatar asked Jul 20 '26 23:07

Ronnie Overby


2 Answers

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.

like image 125
Matt Murrell Avatar answered Jul 22 '26 11:07

Matt Murrell


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.

like image 39
Joel Coehoorn Avatar answered Jul 22 '26 12:07

Joel Coehoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!