Welcome to AspAdvice Sign in | Join | Help

Move the ViewState off the client and cache it on the server

Recently Wally McClure did a PodCast titled ASP.NET 2.0 Page Persistence. I thought I would take Wally's idea and utilize the Microsoft Enterprise Library 3.0 and persist the ViewState to a cache object.

To implement this method you must of course download and install Enterprise Library 3.0 and establish the appropriate references within your project. In the case of this example I have simply created a base class that the web pages will inherit.

Here is a screenshot with the ViewState that is persisted to the client:

Next I have created a cache manager specifically to handle the ViewState:

Now for the base page. 

public class CachePageStatePersister : Page
{
    CacheManager viewStateCacheManager = CacheFactory.GetCacheManager("ViewState Cache Manager");

    /// <summary>
    /// Loads any saved view-state information to the <see cref="T:System.Web.UI.Page"></see> object.
    /// </summary>
    /// <returns>The saved view state.</returns>
    protected override object LoadPageStateFromPersistenceMedium()
    {
        object viewStateBag;

        try
        {
            viewStateBag = viewStateCacheManager.GetData(GetSessionId());
        }
        catch
        {
            throw new HttpException("The View State is empty");
        }

        return viewStateBag;
    }

    /// <summary>
    /// Saves the page state to persistence medium.
    /// </summary>
    /// <param name="viewStateBag">The view state bag.</param>
    protected override void SavePageStateToPersistenceMedium(object viewStateBag)
    {
        viewStateCacheManager.Add(GetSessionId(), viewStateBag);
        return;
    }

    /// <summary>
    /// Gets the session id.
    /// </summary>
    /// <returns></returns>
    public string GetSessionId()
    {
        return Session.SessionID.ToString();
    }
}

At this point the ViewState is cached on the server and you can see the difference first hand.

You can clearly see the original page size was 44KB and now the page saize is 27KB.

Be sure to listen to Wally's PodCast if you are intersted in employing SQL Server for managing the ViewState.. Good luck!

Sponsor
Published Saturday, April 28, 2007 6:53 PM by sswafford

Comments

New Comments to this post are disabled