May 17, 2006 When you are developing an ASP.NET web form, you want to make sure that the viewstate
isn't larger than it has to be. The more viewstate you've got, the longer the page
takes to render in the browser. I have often seen gigantic viewstates, larger than
50 kb in size. For obvious reasons, this is not desirable if it can be avoided without
breaking any functionality.
To test the size of the viewstate, just view the source code and count the lines of
the hidden input field where the viewstate resides. This is not a very accurate measure
but the is an easier way. Before deploying the final website to the public, you can
add this method to the page and it will print out the number of characters in the
viewstate. This is a much faster way of testing it for optimization.
using System.Text.RegularExpressions;
protected override void Render(HtmlTextWriter
writer)
{
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);
base.Render(htmlWriter);
string viewstate = GetViewstate(sw.ToString());
Response.Write(viewstate.Length);
writer.Write(sw.ToString());
}
private string GetViewstate(string html)
{
Regex regex = new Regex("(<input.*?__VIEWSTATE.*?/>)", RegexOptions.IgnoreCase);
Match match = regex.Match(html);
if (match.Success)
{
int start = match.Captures[0].Value.IndexOf("value=\"") + 7;
int stop = match.Captures[0].Value.LastIndexOf("\"");
return match.Captures[0].Value.Substring(start, stop - start);
}
return string.Empty;
}
These methods will output the length of the viewstate string, to make it easy to test
the size.
You could also just use the Test
Browser to get this information.
* $4.95/month BlogEngine.net Hosting – Click Here!