Thursday, 3 May 2012

ASP.Net 4.0 Report Viewer Control "Failed to load viewstate" Error

I spent almost an entire day trying to fix a problem with a Report Viewer Control (version 10.0.0) i used to render a remote report on a ASP.Net(4.0) application.

The error was not initially obvious as one of the (dynamic) parameters loaded on the page with the report control, when the page first loads. But when i choose a value from the first parameter, to dynamically populate the other parameter, the entire Report Viewer Control gets disabled(see figure below).






I got stuck here for over 5 hours, and searched virtually everywhere on the web to get a solution. Apparently, a couple of other developers had experienced this issue and struggled to find a solution. After digging a little bit further(you guessed right, i checked the Event Viewer), i found this error:

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.
I started another round of "Googling" to find  the solution, but this even made it worse. While most people simply ignored the question most places it was asked, those who answered on the blogs i saw, gave all sorts of answers, some probably more complex than the problem at hand. :)

Anyways, it appears the problem has to the with ASP.Net ViewState and the way PostBack is handled. Since the Report Viewer Control requires a  Script Manager control on the page, it's obvious that it does post backs asynchronously. Some solutions suggest setting EnableViewState = "false" but this will not work because the Report Viewer control requires State information. Another alternative is to use an UpdatePanel, but it seems it didn't work for most people who tried it.

For me, after trying everything, and putting all i said above together, i decided to go traditional by allowing Post-backs in a Synchronous mode. So i set the AsyncRendering ="False", and InteractivityPostBackMode="AlwaysSynchronous" and it fixed my problem.

For record, i was loading a remote report (from another server) but am certain it has nothing to do with whether it's a local or remote report.

I hope this helps someone.