views:

167

answers:

6

What are the latest and greatest ways to compress the ASP.NET ViewState content?

What about the performance of this? Is it worth it to keep the pages quick and minimize data-traffic?

How can I make:

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" 
value="/wEPDwUKMTM4Mjc3NDEyOWQYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgkFLGN0b
DAwJENvbnRlbnRQbGFjZUhvbGRlcl9NYWluQ29udGVudCRSYWRCdXQxBSxjdGwwMCRDb250ZW50UGxhY2VIb
2xkZXJfTWFpbkNvbnRlbnQkUmFkQnV0MQUsY3RsMDAkQ29udGVudFBsYWNlSG9sZGVyX01haW5Db250ZW50J
FJhZEJ1dDIFLGN0bDAwJENvbnRlbnRQbGFjZUhvbGRlcl9NYWluQ29udGVudCRSYWRCdXQyBSxjdGwwMCRDb
250ZW50UGxhY2VIb2xkZXJfTWFpbkNvbnRlbnQkUmFkQnV0MwUsY3RsMDAkQ29udGVudFBsYWNlSG9sZGVyX
01haW5Db250ZW50JFJhZEJ1dDQFLGN0bDAwJENvbnRlbnRQbGFjZUhvbGRlcl9NYWluQ29udGVudCRSYWRCd
XQ0BSxjdGwwMCRDb250ZW50UGxhY2VIb2xkZXJfTWFpbkNvbnRlbnQkUmFkQnV0NQUsY3RsMDAkQ29udGVud
FBsYWNlSG9sZGVyX01haW5Db250ZW50JFJhZEJ1dDXz21BS0eJ7991pzjjj4VXbs2fGBw==" />

Into sometning like this:

<input type="hidden" name="__VIEWSTATE"  id="__VIEWSTATE" 
value="/wEPDwUKMTM4Mjc3N==" />
+1  A: 

The best way to minimize the view state is just to not use it. It will cause you to do some extra work programming (repopulating control values etc on post back, but it will save you on the amount of information you send to the browser). You can't tamper with it.

Here is a link to the view state on MSDN:

http://msdn.microsoft.com/en-us/library/ms972976.aspx

Here is a link describing some best practices:

http://mnairooz.blogspot.com/2007/01/aspnet-20-viewstate-and-good-practices.html

And One on disabling the ViewState:

http://www.codeproject.com/KB/aspnet/ASPNET_Best_Practices.aspx

Kevin
If one is going to repopulate controls, then why even bother using the ASP.NET Web form abstraction in the first place? Obviously, since Seb tagged this as asp.net-webforms" this is not an option.
IrishChieftain
You can use web forms without the view state. People do it all the time. There are a ton of tings that the controls handle for you without even touching the viewstate.
Kevin
Repopulating controls is not one of them - that's why we use Web forms in the first place. I think the point is to turn it off selectively for controls that do not need it.
IrishChieftain
Actually, you can repopulate controls without the view state.
Kevin
+6  A: 

The simple answer might not be what you want to hear. Too often, controls on the page have viewstate by default when they really don't need it. It's a good idea to switch off viewstate until you know you're going to need it, and only switch it on for the (hopefully) few cases where you actually want to keep the view state.

Bernhard Hofmann
+1 I think we are all guilty of not checking our pages for this.
IrishChieftain
+0.5, but there are too many cases where ASP.Net controls require ViewState even when they have no legitimate reason to require it. For example, if I recall correctly, events raised from controls within DataGrid/DataView/DataList won't correctly get called if the datagrid has viewstate disabled (even though the postback with correct parameters is still done on the client side)
ckarras
+5  A: 

Seb, ViewState is already compressed... that is what you are seeing... a compressed version of your controls. If you want less overhead, then don't use viewstate :)

Viewstate use should be kept to a minimum!

Polaris878
ViewState is only base-64 encoded. It is not "compressed"unless you consider base-64 compression.
Thomas
That's true, but his overall point isn't wrong either. Base64's composition is very difficult to compress with standard algorithms. Trying to gain significant ViewState savings through compression is futile.
Dave Ward
+3  A: 
  1. Avoid using ViewState
  2. Use compression on the IIS server.
  3. You can wireup something that will compress the viewstate into and out of a page by doing something like:
public abstract class PageBase : System.Web.UI.Page
{
    private ObjectStateFormatter _formatter = new ObjectStateFormatter();

    private static byte[] Compress( byte[] data )
    {
            var compressedData = new MemoryStream();
            var compressStream = new GZipStream(output, CompressionMode.Compress, true);
            compressStream.Write(data, 0, data.Length);
            compressStream.Close();
            return compressedData.ToArray();
    }
    private static byte[] Uncompress( byte[] data )
    {
            var compressedData = new MemoryStream();
            input.Write(compressedData, 0, compressedData.Length);
            input.Position = 0;
            var compressStream = new GZipStream(compressedData, CompressionMode.Decompress, true);
            var uncompressedData = new MemoryStream();
            var buffer = new byte[64];
            var read = compressStream.Read(buffer, 0, buffer.Length);

            while (read > 0)
            {
                uncompressedData.Write(buffer, 0, read);
                read = compressStream.Read(buffer, 0, buffer.Length);
            }
            compressStream.Close();
            return uncompressedData.ToArray();
    }
    protected override void SavePageStateToPersistenceMedium(object viewState)
    {
        var ms = new MemoryStream();
        _formatter.Serialize(ms, viewState);
        var viewStateBytes = ms.ToArray();
        ClientScript.RegisterHiddenField("__COMPRESSED_VIEWSTATE"
            , Convert.ToBase64String( Compress(viewStateArray)) );
    }
    protected override object LoadPageStateFromPersistenceMedium()
    {
        var compressedViewState = Request.Form["__COMPRESSED_VIEWSTATE"];
        var bytes = Uncompress( Convert.FromBase64String( compressedViewState ) );
        return _formatter.Deserialize( Convert.ToBase64String( bytes ) );
    }
}
Thomas
Presumably if you use this you'll also need to delete the original Viewstate hidden field as well?
Graham Clark
In the Save...() method, I'd check whether viewStateBytes or Compress(viewStateBytes) is smaller, and then either write a __VIEWSTATE (with uncompressed), or __COMPRESSED_VIEWSTATE. No point sending the compressed version if it turns out to be larger.
Damien_The_Unbeliever
@Graham - Actually no. You are intercepting the calls that would save to the normal hidden __VIEWSTATE field so it will be empty.
Thomas
@Damien - That's not a bad idea. I'd be interesting to determine if there is a significant performance difference. It is also possible that if the data is small enough that the compressed version will come out larger than the uncompressed version. In some cases I've implemented an abstract "EnableViewStateCompression" property that derived pages can override and set to false if desired.
Thomas
A: 

This is an XML-lized visualization of your posted viewstate:

<viewstate>
  <Pair>
    <Pair>
      <String>1382774129</String>
    </Pair>
  </Pair>
</viewstate>
<controlstate>
  <HybridDictionary>
    <DictionaryEntry>
      <String>__ControlsRequirePostBackKey__</String>
      <ArrayList>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut1</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut1</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut2</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut2</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut3</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut4</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut4</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut5</String>
        <String>ctl00$ContentPlaceHolder_MainContent$RadBut5</String>
      </ArrayList>
    </DictionaryEntry>
  </HybridDictionary>
</controlstate>

Basically just a few radiobuttons which like to know of their existance. (browsers don't send an <input type="radio"> field with the postdata if it is not checked). This is pretty minimal already.

It can likely be compressed by hooking in the load/save methods or HTTP modules, but this may not be really practical nor really needed.


In case the viewstate is much bigger in your real app, avoid getting objects in the viewstate at all. This can be achieved by initializing the controls in the OnInit() or Page_Init() methods instead of the default Page_Load().

The rationale behind this can be found at http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx and http://msdn.microsoft.com/en-us/library/ms972976.aspx

A quick summary:

  • ViewState is just the backing store for almost all control properties, including defaults.
  • After the defaults are set by OnInit(), the TrackViewState() method will is called.
  • Any subsequent changes (e.g. by Page_Load()) or an eventhandler, will be tracked and submitted to the client. This way those controls can restore their state at the next request.
  • Instead of relying at the framework to restore objects, restore objects in OnInit() when needed. (e.g. repopulating the options of a DropDownList from the database).

One exception:

If a control is dynamically added to the control tree, it plays a catch-up. Their OnInit() method may run at a later moment, causing those properties to end up in the viewstate after all. If the initialization of the control can't happen in OnInit(), setting EnableViewState="false" can be used as workaround.

Each time my viewstate grows unexpectedly, I'm using the "ViewState Decoder 2.2" app to find out what ended up in the viewstate. Often, it's not needed for the data to be there.

And a final word:

The viewstate is not used for repopulating forms!! Those values are already submitted with the postdata.

vdboor
A: 

Again, after some research into this I summarized my findings in a blog-post about Compressing View State.

To save a compressed View State, this is what I did:

protected override void SavePageStateToPersistenceMedium(object state) {
    SaveCompressedPageState(state);
}

private void SaveCompressedPageState(object state) {
    byte[] viewStateBytes;
    using(MemoryStream stream = new MemoryStream()) {
        ObjectStateFormatter formatter = new ObjectStateFormatter();
        formatter.Serialize(stream, state);
        viewStateBytes = stream.ToArray();
    }

    byte[] compressed = CompressionHelper.Compress(viewStateBytes);
    string compressedBase64 = Convert.ToBase64String(compressed);

    ClientScript.RegisterHiddenField(ViewStateFieldName, compressedBase64);
}

And for the loading-part, this code made it work for me:

protected override object LoadPageStateFromPersistenceMedium() {
    return LoadCompressedPageState();
}

private object LoadCompressedPageState() {
    string viewState = Request.Form[ViewStateFieldName];
    if(string.IsNullOrEmpty(viewState)) {
        return string.Empty;
    }

    byte[] decompressed = CompressionHelper.Decompress(viewState);
    string decompressedBase64 = Convert.ToBase64String(decompressed);

    ObjectStateFormatter formatter = new ObjectStateFormatter();
    return formatter.Deserialize(decompressedBase64);
}
Seb Nilsson