Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove or compress your asp.net viewstate

Just spent a lot of time exorcising asp.net's large (but understandably useful) viewstate from an app, and i think it's worth sharing how it's done.

Basically, i want this question to be open to all solutions for shrinking/compressing/removing viewstate.

like image 526
Chris Avatar asked Jan 17 '11 22:01

Chris


People also ask

Does ViewState affect performance?

To accomplish our tasks, we use ViewState a lot, but as we know, it doesn't come free - it has a performance overhead. The ViewState is stored on the page in the form of a hidden variable. Its always advised to use the ViewState as little as possible. We also have other ways to reduce the performance overhead.

What is the ideal size of a ViewState?

If it's an internal company application and doesn't have a lot of users, a bigger viewstate(200-500k) may be acceptable. If it's on the web or a lot of users will be on it, you should limit the viewstate. To limit viewstate, look at ways to improve your UI so it's not as complicated.

What is ViewState in asp net c#?

View state is the method that the ASP.NET page framework uses to preserve page and control values between round trips. When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings.


2 Answers

First easy option, use the built-in SessionPageStatePersister class. What this does is keep the viewstate on the session on the server, rather than sending it to the client. However, it still sends a smaller viewstate down so isn't all roses:

using System.Web.UI;
... the following goes in your Page class (eg your .aspx.cs) ...
PageStatePersister pageStatePersister;
protected override PageStatePersister PageStatePersister
{
  get
  {
    // Unlike as exemplified in the MSDN docs, we cannot simply return a new PageStatePersister
    // every call to this property, as it causes problems
    return pageStatePersister ?? (pageStatePersister = new SessionPageStatePersister(this));
  }
}

This method shrunk a particularly large postback from 100k to 80k. Not great, but a good start.

like image 194
Chris Avatar answered Nov 09 '22 00:11

Chris


Switch to ASP.NET MVC! No ViewState!

like image 29
Simon_Weaver Avatar answered Nov 09 '22 00:11

Simon_Weaver