>
 





ViewState is the built-in structure for automatically retaining values between multiple requests for the same page in ASP.NET. In other words, ViewState technology saves/restores page state between postbacks. On the other hand, this technology comes with an overhead that affects performance especially during page load since the state data is maintained in a hidden field.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJLTMzMTY4NDI5ZGRrYY+UdQNeb33gRiGcw2LoiMHduA==" />

Reducing ViewState Size

We can completely disable viewstate by setting EnableViewState to false in the page directive but you need extra programming effort for you to take care of the page state. It is a good idea to disable ViewState for the controls that do not actually need it such as Literals and Labels by setting EnableViewState to false. But this do not entirely solve the problem. 

Compressing ViewState

ASP.NET 2.0 comes with the System.IO.Compression namespace, which contains classes with functionality to compress/decompress streams. In ASP.NET 1.1, developers must use third party compression tools such as ICSharpCode.SharpZipLib to compress viewstate.

Compressing/Decompressing using GZipStream

The following class contains two methods for compressing and decompressing a stream.  

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.IO.Compression;

public static class CompressViewState
{
    public static byte[] Compress(byte[] data)
    {
        MemoryStream output = new MemoryStream();
        GZipStream gzip = new GZipStream(output,
                          CompressionMode.Compress, true);
        gzip.Write(data, 0, data.Length);
        gzip.Close();
        return output.ToArray();
    }

    public static byte[] Decompress(byte[] data)
    {
        MemoryStream input = new MemoryStream();
        input.Write(data, 0, data.Length);
        input.Position = 0;
        GZipStream gzip = new GZipStream(input,
                          CompressionMode.Decompress, true);
        MemoryStream output = new MemoryStream();
        byte[] buff = new byte[64];
        int read = -1;
        read = gzip.Read(buff, 0, buff.Length);
        while (read > 0)
        {
            output.Write(buff, 0, read);
            read = gzip.Read(buff, 0, buff.Length);
        }
        gzip.Close();
        return output.ToArray();
    }

You need to save this class in a .cs file in the App_Code directory.

Utilizing the CompressViewState Class

In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.

The folowing code creates a BasePage class which inherits from System.Web.UI.Page, and web pages using the following Base Page class as the base class utilizes ViewState compression. The BasePage class adds an additional hidden field __COMPRESSEDVIEWSTATE, to store the compressed ViewState.

using System;
using System.IO;
using System.IO.Compression;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Configuration;
using System.Threading;
using System.Globalization;
using System.Text;

public abstract class BasePage : System.Web.UI.Page
{
    private ObjectStateFormatter _formatter =
        new ObjectStateFormatter();

    protected override void
        SavePageStateToPersistenceMedium(object viewState)
    {
        MemoryStream ms = new MemoryStream();
        _formatter.Serialize(ms, viewState);
        byte[] viewStateArray = ms.ToArray();
        ClientScript.RegisterHiddenField("__COMPRESSEDVIEWSTATE",
            Convert.ToBase64String(
            CompressViewState.Compress(viewStateArray)));
    }
    protected override object
        LoadPageStateFromPersistenceMedium()
    {
        string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
        byte[] bytes = Convert.FromBase64String(vsString);
        bytes = CompressViewState.Decompress(bytes);
        return _formatter.Deserialize(
            Convert.ToBase64String(bytes));
    }
}

Demo

Demo project contains two web pages. You may compare the compression performance using the demo project.

 

An online demo web page without viewstate compression.
An online demo web page with viewstate compression.

If you view the HTML of the page with viewstate compression, the __VIEWSTATE field is empty, while our __COMPRESSEDVIEWSTATE field contains the compressed ViewState, encoded in Base64.

ViewState Compression Performance

After few tests using the demo project, ViewState size is reduces by 40 - 60% resulting shorter response times for users and less bandwidth need for site owners.

Compression, decompressing, encoding and decoding data is a quite heavy work for the server so while you are saving from bandwidth and offering shorter response times for users, you are having a performance hit on the server's hardware.

Want automatic updates? Subscribe to our RSS feed or
Get Email Updates sent directly to your inbox!

Currently rated 5.0 by 5 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5


Comments

November 15. 2007 21:11

Nice article with even nicer ending. Exactly, compression is a big hit for the server. So my 2 questions:

1. IIS 6.0 compression probably won't help, will it? As I understand viewstate is already "compressed" or hashed so IIS compression won't help in compressing hidden fields data (it will help on other page elements).

2. I think it is better to store viewstate on a server in a session state. That way you save CPU cycles by not compressing it and bandwith by not sending it.

all in all ASP.NET viewstate is extremelly big topic, any addition or research is welcome, but personally I don't think compression is the right way. In some cases we could have 1000 users reading just one page but with 1000 different viewstate's data, even when using cache this would be no win for the server CPU performance when compressing this goodie ;)

steve raynold | Reply

November 27. 2007 15:29

Hi,
I implemented your solution, however, it looks like ControlState is no longer working when using the compressed viewstate page.

Kind regards,
Henk

Henk | Reply

December 2. 2007 23:51

Thank for doing the hard work for us. I was under the impression that ASP.NET 2.0 already compressed the ViewState, but it clearly does not since this code has reduced my ViewState in one page from 47Kb down to 9kB! Why did Microsoft not compress ViewState by default?

Dave Bartlett | Reply

January 18. 2008 10:41

Seams to be a fine thing. But what about server side performance?
In every page request the server executes the compression code.
Couldn't be a problem for the web server performance if your site has very much page impressions?

ltrader

ltrader | Reply

February 21. 2008 12:15

doesnt work with wizard control Frown

dom | Reply

June 2. 2008 11:31

cool news

senol | Reply

June 2. 2008 11:31

cool news

senol | Reply

December 11. 2008 06:44

Really very nice code.

But I am getting a problem. Viewstate is not maintained for some controls on the page or controls do not retain their values after postback.

May you plz suggest, is there any more settings required to overcome this problem?

Thanks in Advaced
Paresh Rathod
Senior Software Engineer

Paresh Rathod | Reply

December 12. 2008 23:18

Oh, sorry, here is the screenshot for the error.

mut | Reply

January 30. 2009 21:24

Thank for doing the hard work for us. I was under the impression that ASP.NET 2.0 already compressed the ViewState, but it clearly does not since this code has reduced my ViewState in one page from 47Kb down to 9kB! Why did Microsoft not compress ViewState by default?

evden eve nakliyat | Reply

February 4. 2009 08:55

Works well . But just a concern for server side

Sneha | Reply

February 24. 2009 22:23

I implemented your solution, however, it looks like ControlState is no longer working when using the compressed viewstate page. Evden eve nakliye ve evden eve nakliyat.

evden eve nakliyat | Reply

February 28. 2009 03:55

Really nice imformation

Matta | Reply

March 2. 2009 17:49

Thanks Thanks for information.

evden eve nakliyat | Reply

March 9. 2009 17:41

I too have run into some compatibility issues implementing viewstate compression, which, IMO, are a deal breaker for this solution.

Rick | Reply

September 24. 2009 09:04


Very Clear and straight forward explanation.

Sealey Tools | Reply

October 8. 2009 09:09

Pingback from topsy.com

Twitter Trackbacks for
        
        How To: Compress ViewState in ASP.NET 2.0 - ViewState Compression with System.IO.Compression
        [bloggingdeveloper.com]
        on Topsy.com

topsy.com | Reply

October 12. 2009 17:16

Topic which you have discussed is very useful and valuable.

SEO | Reply

October 15. 2009 13:02

thanks!  very helpful post!! like the template btw ;)

personal loans | Reply

October 28. 2009 15:24

betsson sitesi. çatlat hadi çatlat yak beni yakabilirsen aaahhhaaaahhh

betsson | Reply

October 28. 2009 15:33

As for me I would read your blog all night long but I have kids and need to share my time between your blog and them.

web design | Reply

October 28. 2009 17:30

thanksss

evden eve nakliyat | Reply

October 31. 2009 10:48

Works well . But just a concern for server side

nice post thankls

fx15 | Reply

November 17. 2009 23:39

Thank you very successful and useful site I have received the necessary information ...

evden eve nakliyat | Reply

November 18. 2009 11:48

I too have run into some compatibility issues implementing viewstate compression, which, IMO, are a deal breaker for this solution.

fx15 | Reply

November 19. 2009 13:59

Works well ,Thanks for information.

Ali | Reply

November 19. 2009 15:51

As for me I would read your blog all night long but I have kids and need to share my time between your blog and them.

evden eve nakliyat | Reply

November 20. 2009 09:23

work perfectly in practice, no problem
Thanks admin

Ali | Reply

November 27. 2009 13:19

nice good

evden eve nakliyat | Reply

December 6. 2009 20:43

nice post thanks

evden eve nakliyat | Reply

December 6. 2009 20:45

great post thank you very much. !

fx15 | Reply

December 9. 2009 13:30

harıka olmuş arkadaşım harıka tek kelime saolun

evden eve nakliyat | Reply

December 14. 2009 10:22

Hi,
SEO expense is a capital expenditure which increases your asset and should never be treated as expense, since it adds value (not cost) to your site.

abercrombie fitch sale | Reply

December 26. 2009 19:26

Nice post . keep up the good work

cash loans | Reply

December 28. 2009 17:18

thenks admin very good

evden eve nakliyat | Reply

January 1. 2010 14:57

thanks admin very good

evden eve nakliyat | Reply

January 11. 2010 15:36

Thanks admin good information

Ali | Reply

January 22. 2010 10:58

this is really good information..

evden eve nakliyat | Reply

January 25. 2010 14:56

thanks for useful codes

evden eve nakliyat | Reply

January 25. 2010 15:00

thanks for these codes

evden eve nakliyat | Reply

March 2. 2010 07:45

Very useful info. Hope to see more posts soon!

melbourne website designers | Reply

March 6. 2010 13:26

IIS 6.0 compression probably won't help, will it? As I understand viewstate is already "compressed" or hashed so IIS compression won't help in compressing hidden fields data (it will help on other page elements).

Bursa haber | Reply

Add comment




(Will not be displayed!)