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
This is an XML-lized visualization of your posted viewstate:
1382774129
__ControlsRequirePostBackKey__
ctl00$ContentPlaceHolder_MainContent$RadBut1
ctl00$ContentPlaceHolder_MainContent$RadBut1
ctl00$ContentPlaceHolder_MainContent$RadBut2
ctl00$ContentPlaceHolder_MainContent$RadBut2
ctl00$ContentPlaceHolder_MainContent$RadBut3
ctl00$ContentPlaceHolder_MainContent$RadBut4
ctl00$ContentPlaceHolder_MainContent$RadBut4
ctl00$ContentPlaceHolder_MainContent$RadBut5
ctl00$ContentPlaceHolder_MainContent$RadBut5
Basically just a few radiobuttons which like to know of their existance. (browsers don't send an 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:
OnInit()
, the TrackViewState()
method will is called.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.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.