Store Viewstate in persistent medium or secondary medium

This article describes how to store viewstate in persistent medium (e.g: Server's hard-drive, or in database) to decrease the weight of any webpage. This can be done by overriding "SavePageStateToPersistenceMedium" and "LoadPageStateFromPersistenceMedium" methods.

Viewstate is a very helpful thing in ASP.NET only if it is used properly.

Viewstate can be tampered and excess use of viewstate makes the page heavier.
You can disable Viewstate of the page or individual controls to make page lighter.
But in cases where you can't disable viewstate for any page or any control, or in places where the page is heavier after optimization also, you can store viewstate value in secondary memory.

To achieve that you need to override two methods
1. SavePageStateToPersistenceMedium
2. LoadPageStateFromPersistenceMedium

First method is used to save viewstate to secondary storage and second one is used to load viewstate value from secondary storage.

The following code describe what to do:

protected override void SavePageStateToPersistenceMedium(object state)
FileStream objFileStream = new FileStream(@"D:\TempViewState.txt", FileMode.OpenOrCreate, FileAccess.Write);
LosFormatter formatter = new LosFormatter();

formatter.Serialize(objFileStream, state); // Serializes viewstate object and stores it in the file.
objFileStream.Close(); // Closes the file to release the resource.


protected override object LoadPageStateFromPersistenceMedium()
FileStream objFileStream = new FileStream(@"D:\TempViewState.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(objFileStream);

// Read the file content and closes the file.
string state = reader.ReadToEnd();

// Deserialize the file content.
LosFormatter lof = new LosFormatter();
return lof.Deserialize(state);

Here in SavePageStateToPersistenceMedium method I am storing the viewstate in a file names TempViewState.txt present in D:drive.
And in LoadPageStateFromPersistenceMedium method I am getting the file content (the viewstate value), which is used by the page.

As this includes some processing, it has some impact on performance also.
So decide yourself before using this approach.



Guest Author: Friday20 Feb 2012

This style is actually amazing! You certainly know how to keep the readers amused. Involving the wit as well as your movies, I was nearly gone to live in start my own weblog (well) Great job. I really loved that which you needed to say, and more than that, how you offered this. Too cool!

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: