August 11, 2008 by Christoff Truter C# ASP.NET Coding Horrors
ASP.net at the bottom of it all mainly builds on sessionless
technologies. The object instances on a web form essentially dies as soon as our
rendered output reaches the browser.
Since we can't work with dead objects, Microsoft came up with a mechanism that "hibernates"
objects and "re-awakens" them as soon as we need them.
This mechanism is called viewstate, which primary function is to persist the state
of web forms, across postsbacks.
The web form contains a hidden field, which houses a serialized copy of the last
state of the page.
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwNjc4NTIwMWRkemG0USJ6hDi/MgWFObHK2J15A3w=" />
To give you an idea, I once saw viewstate
big enough to fill my 10mb harddrive back in the day.
protected string ViewStateFileName
{
get
{
string vKey = (String.IsNullOrEmpty(Request.Form["viewstatekey"]))
? Guid.NewGuid().ToString() : Request.Form["viewstatekey"];
ClientScript.RegisterHiddenField("viewstatekey", vKey);
return ResolveUrl("~/viewstate/" + vKey);
}
}
protected override object LoadPageStateFromPersistenceMedium()
{
if (File.Exists(ViewStateFileName))
{
using (StreamReader stream = new StreamReader(ViewStateFileName))
{
LosFormatter formatter = new LosFormatter();
return formatter.Deserialize(stream);
}
}
else
{
return null;
}
}
protected override void SavePageStateToPersistenceMedium(object state)
{
using (StreamWriter stream = new StreamWriter(ViewStateFileName))
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
}
}
protected override void SavePageStateToPersistenceMedium(object state)
{
if (Debugger.IsAttached)
{
using (MemoryStream stream = new MemoryStream())
{
LosFormatter formatter = new LosFormatter();
formatter.Serialize(stream, state);
if ((stream.Capacity / 1024) > 32)
{
throw new Exception("Please optimize viewstate");
}
}
}
base.SavePageStateToPersistenceMedium(state);
}
Re:Deprecated October 1, 2009 by Anonymous
Thanks a lot..