Monday, July 2, 2007

Remove ViewState from the page

Need to optimize your ASPX pages for Search Engines like Google? One thing You have to do is to minimize or delete the viewstate hidden input field. Please find the solution below.

public class BasePage : Page
{
protected override void SavePageStateToPersistenceMedium(object viewState)
{
string vsKey = String.Format("VIEWSTATE_{0}_{1}_{2}", base.Session.SessionID, Request.RawUrl, DateTime.Now);
Session.Add(vsKey, viewState);
ClientScript.RegisterHiddenField("__VIEWSTATE_KEY", vsKey);
}

protected override object LoadPageStateFromPersistenceMedium()
{
string vsKey = Request.Form["__VIEWSTATE_KEY"];
return Session[vsKey];
}
}

3 comments:

Anonymous said...

Hi all!

Thank you very much for the example. It works for me. Great!

Anonymous said...

Instead of
ClientScript.RegisterHiddenField (...)

I'd suggest you to use
ScriptManager.RegisterHiddenField(...)

The ClientScript is buggy when using ASP.NET Ajax...

Anonymous said...

This is great, cleaned it up nicely. What are your thoughs on saving it to the Database instead of a session?