Tuesday, September 17, 2013

Using ReportViewer in ASP.NET MVC

About three and a half years ago I was tasked with building a reporting portal. I elected to go with ASP.NET MVC due to the fact that most of the rest of my department was a Ruby shop. I figured if anyone else would have to come in and work on it, at least they wouldn't have to struggle with the idea of ASP.NET WebForms.

Now one challenge was that this was a publicly facing site, but the reports could only be seen by authenticated users with the right permissions. The main challenge however is the fact that ReportViewer requires that a page be able to store Session State. By definition MVC is Stateless.

So how do we solve this problem? Luckily the folks at Microsoft allowed us to have WebForms and MVC applications side by side. So the simplest solution is to just include a new webform page as part of the Solution.

The first thing we need to do is get our criteria. I'm assuming that you want to pass in some parameters to the ReportViewer, so lets grab those from our Form Collection and build our Action.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BuildReport(FormCollection collection)
{
       try
      {
            // Load Form Data into a report object
            DynamicReport report = new DynamicReport( collection["AccountName"], Convert.ToDateTime(collection["StartDate"]), Convert.ToDateTime(collection["EndDate"]));
           // Save Report to Session
           Session["Report"] = report;
           //Redirect to Reports WebForm Page
            Response.Redirect("../Report.aspx");
        }
        catch (Exception e)
        {
                  return RedirectToAction("Error", new { id = (int)ErrorCode.Unknown });
        }
}

Its just that easy. Can't believe this has been sitting in draft status for that long....
          

No comments:

Post a Comment