Storing ViewState in MongoDb Database

ViewState can serve as both good and evil. Good because it allows to persist the ASP.NET control state during postbacks. Evil because it makes the page size larger and causes more bandwidth to be consumed. In this article we are going to demonstrate how to move the ViewState out of the page and store it in a MongoDb database.

Why MongoDb?

There are several places to store ViewState which includes file system, relational database etc. But all these storage mechanisms require some effort to pull the data out of them and usually the speed at which the data is retrieved is not very fast. MongoDb provides a dictionary based storage system which works using pointers. It is extremely fast and fits perfectly for these kind of operations.

Implementing a BasePage:

Since, all of the pages will use MongoDb as their ViewState storage. It is a good idea to introduce a BasePage from which all the other pages of the application will derive. This way all the pages will automatically inherit the functionality to store ViewState in the MongoDb database.

The two methods implemented in the BasePage are LoadPageStateFromPersistentMedium and SavePageStateToPersistentMedium. The implementation is shown below:

We are using LosFormatter to serialize and deserialize the ViewState. We are using our custom class MongoViewStateManager to Save and Load the ViewState from the database.

Implementing MongoViewStateManager:

MongoViewStateManager is responsible for Loading and Saving the ViewState into the MongoDb database. The database is called "PageViewStates" and the ViewState is stored in the "ViewStateCollection" table. The implementation is shown below:

The ViewState is only inserted if it does not exist in the table. If the ViewState already exist in the table then it is updated. The GetByKey method is used to fetch the document from the MongoDb database. The implementation of GetByKey is shown below:

Finally, we need to load the ViewState back by the BasePage. This is performed by the Load method of the MongoViewStateManager class. The implementation is shown below:

One important thing to note is the Key used to store and retrieve the ViewState. We are using URL path and query as a key but feel free to use any key you prefer.

Run the application and view the source and you will notice that the ViewState is not present in the source of the page. All the ViewState has been transfered to the MongoDb database. The screenshot below shows the documents inside the MongoDb database.

UPDATE:

Mike Mason pointed out that the keys should be unique for all the users and should not be shared since it is a ViewState and not Cached items. The updated code to create the key is as follows:

Conclusion:

In this article we demonstrated how to extract the ViewState out of the page and store it in MongoDb database. This will make the page size smaller and page load faster.