Wednesday, November 05, 2008

.NET | Failed to load viewstate ?

Hello,
Today I am working on one of our Real State Agent’s website and I came across with the following error:

Server Error in '/' Application.
Failed to load viewstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request.

After a short research I found http://geekswithblogs.net/FrostRed/archive/2007/02/17/106547.aspx which explains in depth what really ViewState: the ViewState tree (type of Triplet or Pair) is NOT the ViewState property (type of StateBag) of the page or any of its controls. You can think it as an object representation of the ViewState value on the html page (the __VIEWSTATE hidden field), which contains all the values need to be written back to the controls during a page postback. If you don't change the default behavior, during the page initialize/load phrase, the ViewState tree will be created by de-serializing the value __VIEWSTATE field by LoadPageStateFromPersistenceMedium(), and the values on the ViewState tree will be put into the controls ViewState bag in LoadViewState() . During the page save/render phrase, the ViewState tree will be created again by SaveViewState (), then serialized and written onto html page by SavePageStateToPersistenceMedium ()”

This help me to have a better understanding of viewstate but did not solve the issue, then I found http://weblogs.asp.net/alessandro/archive/2008/01/04/failed-to-load-viewstate-typical-problem-with-an-obvious-solution.aspx which mentioned that this error can be caused by “changing the order of controls, that is, when your loading a dynamic control, make sure the order in which you create it, has the same order when you recreate it.”

After reading at this article, I noticed that the HTML portion of my Server Control looked like this:
<div><asp:literal id="BizCardTitle" runat="server"></asp:literal></div>
<
div><cc1:remsimage runat="server" id="img_BizCardPhoto"></cc1:remsimage></div>

But my code behind shows:
Me.LoadImage(objContact.ImageID)
LitBizCardTitle.Text = m_objSite.OwnerTitle

Rearranging the controls solve the problem. I recalled changing the order on the HTML portion only. This changed the order in which controls are added after postback. Therefore the viewstate loaded
Me.LoadImage(objContact.ImageID) into LitBizCardTitle.Text and biceverse.

Percy Dyer
.NET Web Application Developer