Testing the size of the viewstate in ASP.NET

by Mads Kristensen 18. May 2006 06:25

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.

* Only $4.95/month ASP.NET & Windows 2008 + IIS 7 Hosting! FREE SQL Included

Tags:

ASP.NET

Comments are closed

About the slave

Mads Kristensen Mads Kristensen
Web developer at ZYB and founder of BlogEngine.NET. More...

LinkedIn ZYB Facebook Last.fm Twitter View Mads Kristensen's profile on Technorati

The Lounge

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008