Introduction

One disadvantage of the ViewSate is it adds extra kilobytes of data to the payload. To overcome this disadvantage, it can be saved on the server.

Strategy

There are three options to save the ViewState on the server.

MS SQL Server

File System

Memory

Using MS SQL Server is expensive. If you do not have MS SQL Server, you have to pay extra money and the speed of it is the lowest. Using memory is expensive too. Because memory is a scarce resource. So, I have chosen to save the ViewSate on the file system.

Using the code

.NET uses the SavePageStateToPersistenceMedium method to save the ViewSate and the LoadPageStateFromPersistenceMedium method to load the ViewSate. I will override these functions to save and load the ViewSate using the file system.

GenerateFileName() generates and registers a file name using the Session ID and a GUID. The ViewState is saved in this file. GetFileName() returns this registered file name.

Performance

Saving ViewState on the page

Saving ViewState on the file system

You can see that the page size and the load time decrease with this method.

Using the demo

You should change the ViewStateRootDirectory in the web.config according to your directory structure. The ASP.NET user must have write permission to this directory.

In the Session_End event, the ViewState storage directory is deleted. In the Application_Start event, ViewStateRootDirectory is loaded to the cache to increase performance instead of reading it from web.config every time.

Comments and Discussions

I used a similar solution with ASP.NET 2.0's PageStatePersister class however I used a GUID key that is sent as the ViewState so that we can work on multiple window & other clashing scenarios. Here is an article on it...