Tuesday, 08 August 2006

In the first article about optimizing rendered page size I have pointed out that you should consider using short names for content placeholders on your master pages because each control's id inside those placeholders is prefixed with the id of the placeholder. But when you look inside the page there is of course another field where you can make some improvements - the ViewState.

There are lot of articles about what you can do to make the ViewState smaller. Mainly - disable it everywhere where it isn't needed. This is a first step you can take. Amongst other things you can also use the SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium methods of the Page class. The purpose of those methods according to MSDN is to save and load any view state information from and to a page object. And that is true. But how to use those methods?

Browsing the results returned by google you can find plenty of solutions out there each unique in its way. Why they are different? The problem with those methods is not saving the state. To save the state you can use anything from the Session object, flat files or even database. The real problem is making sure that when a form is submited to a server, its ViewState is properly loaded - the concrete ViewState that was saved for that concrete page. A solution to just use Session["ViewState"] as a storage medium won't do, because then we can only have one ViewState for each user - no multiple windows/frames allowed.

My solution would be to include a hidden field on each page, name it somehow and use its value as a key for identifying which ViewState to load. Such a hidden field may be added dynamicaly in a base page so no additional work is required when adding new pages to a project. This field of course shoud hold some unique value (such as guid) in order to distinguish one page request from the other.

kick it on DotNetKicks.com