I store a list to the ViewState. Whenever I do a change to the list, the ViewState is automatically updated. When I checked couple of related posts in StackOverflow I learned that because ViewState stores the reference to the List object.
However, I want to learn more about the details. I though the information stored in ViewState travels through PostBacks. Then, the whole list is supposed to be serialized and stored in the hidden field, is that right? If it stores the reference to the List object, then what is the lifetime of the object in the Server memory? Is it re-created each time server receives a request?
Can anyone explain the mechanism for me?
Let me give you a quick example:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string> myList = new List<string> { "a", "b", "c" };
Response.Write(string.Join(";", myList.ToArray()) + "<br>");
ViewState["myList"] = myList;
myList.Add("d");
List<string> myListSavedInViewstate = (List<string>)ViewState["myList"];
Response.Write(string.Join(";", myListSavedInViewstate.ToArray()) + "<br>");
myListSavedInViewstate.Add("e");
Response.Write(string.Join(";", myList.ToArray()) + "<br>");
Response.Write(myList.GetHashCode() + "<br>");
Response.Write(myListSavedInViewstate.GetHashCode() + "<br>");
}
}
The output is:
a;b;c
a;b;c;d
a;b;c;d;e
34781257
34781257
So basically yes, Viewstate keeps a reference not a copy of the object (of reference types) throughout the page life cycle. However as soon as the Request ends the Viewstate is serialized in the hidden field and returned to the client and the Viewstate instance is dropped. When postback occurs, viewstate is deserialized and recreated. The recreated instance of viewstate is however only a shallow copy of all the objects it used to hold references to during page life cycle execution. That is why all classes which are permitted in the viewstate have to implement ISerializable interface (or have to have a Serializable attribute).
This is however only the tip of an iceberg ;) Here is a very nice write up about viewstate if you'd like to read more on the subject.
http://weblogs.asp.net/infinitiesloop/Truly-Understanding-Viewstate