Fixing “Operation is not valid due to the current state of the object” when using SSRS ReportViewer in ASP.Net MVC

So I’ve included the SSRS ReportView control within my ASP.Net MVC application. So far so good. Just displaying the report works fine after struggeling with the dimensions of the iframe and the ReportViewer control itself.

But after a more complex drill-through report was display and then clicking the actions caused the famous error “Operation is not valid due to the current state of the object” (which in this case has nothing to do with resource limits due to security patches). Switching from asynchronous (AJAX) to classic postback did not help either.

It was a long day and the obvious was not that obvious anymore. I used the following code within the Page_Load event to configure the report:

protected void Page_Load(object sender, EventArgs e)
{
  string reportName = Page.RouteData.Values["reportName"] as String;
  string reportPath = Page.RouteData.Values["reportPath"] as String;
  string sizeType = Page.RouteData.Values["sizeType"] as String;
  bool withToolbar = Boolean.Parse(Page.RouteData.Values["withToolbar"] as String);
 
  theReportViewer.ServerReport.ReportServerUrl = new Uri("http://example.org");
  theReportViewer.ServerReport.ReportPath = String.Format("/{1}/{0}", reportName, reportPath);
}

After analysing logfiles and event logs I was nearly giving up when finally realizing that a click within the report causes a postback. But everytime the page loads I resetted the report. *sigh* The “fix” is simple and straightforward and should have been written in the first place.

protected void Page_Load(object sender, EventArgs e)
{
  if (!this.Page.IsPostBack)
  {
    string reportName = Page.RouteData.Values["reportName"] as String;
    string reportPath = Page.RouteData.Values["reportPath"] as String;
    string sizeType = Page.RouteData.Values["sizeType"] as String;
    bool withToolbar = Boolean.Parse(Page.RouteData.Values["withToolbar"] as String);
 
    theReportViewer.ServerReport.ReportServerUrl = new Uri("http://example.org");
    theReportViewer.ServerReport.ReportPath = String.Format("/{1}/{0}", reportName, reportPath);
  }
}

Now drill-through and navigation inside the reports is no problem at all.