size of the viewstate in ASP.NET

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.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewState.aspx.cs" Inherits="ViewState" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="" >
<head runat="server">
<title>Untitled Page</title>
<form id="form1" runat="server">


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
public partial class ViewState : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)

protected override void Render(HtmlTextWriter writer)
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(sw);

string viewstate = GetViewstate(sw.ToString());
writer.Write("Size Of View State");

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;

No comments:

Post a Comment