Search code examples
asp.net-mvc-3crystal-reports

Crystal Reports Viewer with MVC3


I am building an ASP.NET MVC3 web application and I want to build some reports using crystal reports and display them using crystal reports viewer. I searched through the web and i didn't find any solid way of doing it in an MVC3 web application. Do you have any hints/ideas of how to do it?


Solution

  • If you don't mind some hacking it's actually pretty easy. (Assuming CR4VS2010)

    First add a WebForms page to your project and add the crystal reports viewer control to it.

    Verify it added references to:

    CrystalDescisions.CrystalReports.Engine, CrystalDescisions.ReportSource, CrystalDescisions.Shared, and CrystalDescisions.Web.

    Then add a PageRoute to your application leading to the newly added page.

    Finally, and this was the biggest pain the BLANK, you'll need to make Crystal's Image Handler work. There are many supposed ways, both around the net and here at SO, none of them really worked for me so I resorted to cheating:

    public class CrystalImageHandlerController : Controller
    {
        //
        // GET: /CrystalImageHandler.aspx
    
        public ActionResult Index()
        {
            return Content("");
        }
    
        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
    
            var handler = new CrystalDecisions.Web.CrystalImageHandler();
            var app = (HttpApplication)filterContext.RequestContext.HttpContext.GetService(typeof(HttpApplication));
            if (app == null) return;
    
            handler.ProcessRequest(app.Context);
    
        }
    }
    

    Add a route to this controller as /CrystalReportsImageHandler.aspx, this is where CR expects it handler to be. This can also be used in Areas, just change the handler and page routes as needed.

    Bear in mind you will not be able to use your Razor layouts. So you'll need to resort to other means to get visual continuity. (I used IFrames)