Reducing ViewState information in ASP.NET

December 22, 2009 by Manjunath HK · 5 Comments 

Few months ago, my manager came to me with a strange problem that some pages of our application were loaded (or rendered) very slowly in the browser. When the page was saved in the local machine (after rendering, click “Save As…” from the File menu or press Ctrl + S), the file size was huge (some pages were even beyond 3 MB).

A page with MBs in size would definitely be a performance bottle-neck.

Reason:

After a deep look into the source code of the HTML, it was found that the page had huge data in its ViewState field. After the ViewState field was cleared, the page size reduced drastically to a few KBs.

Resolution:

It was mutually decided to store the viewstate in the session (or at the server) if it was possible.

Here is what I did:

1. Add a new class by name PageStateAdapter in the App_Code folder of the website.

Add the following code:

using System.Web.UI;
using System.Web.UI.Adapters;
public class PageStateAdapter : PageAdapter
{
	public override PageStatePersister GetStatePersister()
	{
		SessionPageStatePersister sessionPageStatePersister = null;
		try
		{
			sessionPageStatePersister = new SessionPageStatePersister(this.Page);
			return sessionPageStatePersister;
		}
		catch (ArgumentException argEx)
		{
			return base.GetStatePersister();
		}
	}
}

When you add a .cs class to your ASP.NET project you will be prompted to add this code to an App_Code folder, if you don’t already have one. Answer yes to this prompt.

2. Add a new .browser file in the App_Browsers folder of the website (Name it anything you want to but ensure that the extension is .browser)

Insert the following code at the bottom of the file:

<browser refID="Default">
	<controlAdapters>
		<adapter controlType="System.Web.UI.Page" adapterType="PageStateAdapter" />
	</controlAdapters>
	<capabilities>
		<capability name="requiresControlStateInSession" value="true" />
	</capabilities>
</browser>

Ignore the other default definitions.

After implementing the above code, I tested the application and found that the viewstate was being stored in the session and the size of the pages rendered to the browser were a few KBs in size.

Note:

This solution was applied to an ASP.NET 2.0 application. It worked fine while testing and the customer was very happy with the implementation. A risk in this method is that more memory needs to be installed in the server.

Also, the solution initially had problems when we were redirecting to an error page using Server.Transfer(…) technique. To avoid this, I added, the catch block in the code to return the base class method.

Hope this helps you.