views:

299

answers:

2

Can someone please explain the difference between ViewState and Session?

More specifically, I'd like to know the best way to keep an object available (continuously setting members through postbacks) throughout the lifecycle of my page.

I currently use Sessions to do this, but I'm not sure if it's the best way.

For example:

SearchObject searchObject;
protected void Page_Load(object sender, EventArgs e)
{
     if(!IsPostBack)
     {
         searchObject = new SearchObject();
         Session["searchObject"] = searchObject;
     }
     else
     {
         searchObject = (SearchObject)Session["searchObject"];
     }
}

that allows me to use my searchObject anywhere else on my page but it's kind of cumbersome as I have to reset my session var if I change any properties etc.

I'm thinking there must be a better way to do this so that .NET doesn't re-instantiate the object each time the page loads, but also puts it in the global scope of the Page class?

Please advise. TIA

+2  A: 

Hi there.

If the search object isn't huge in size, then go with using a ViewState. A ViewState is perfect if you only want the object to live for the current page's lifecycle.

A session object is also fine to use, but obviously once the search object is in there, it will be around for longer the page's lifecycle.

Also, one thing I do with ViewState/Session objects is wrap their access with a property:

public object GetObject
        {
            get
            {
                if (ViewState["MyObject"] != null)
                {
                    return ViewState["MyObject"];
                }

                return null;
            }
            set
            {
                ViewState["MyObject"] = value;
            }
        }

I tend to find it cleaner to do it this way. Just change the above code to fit your needs.

http://www.articlesbase.com/programming-articles/how-to-choose-from-viewstate-session-application-cache-and-cookies-443393.html

http://forums.asp.net/t/886104.aspx

Cheers. Jas.

Jason Evans
+1  A: 

First of all Viewstate is per page where as the session exists throughout the application during the current session, if you want your searchobject to persist accross pages then session is the right way to go.

Second of all viewstate is transfered as encrypted text between the browser and the server with each postback, so the more you store in the viewstate the more data is going down to and coming back from the client each time, whereas the session is stored server side and the only thing that goes back and forth is a session identifier, either as a cookie or in the URL.

Whether the session or viewstate is the right palce to store your search object depends on what you are doing with it and what data is in it, hopefully the above explanation will help you decidie the right method to use.

Ben Robinson