Rendering Reports using ASP.NET MVC

DevExpress Data Blog
21 October 2010

MacgyverAlthough there is no ASP.NET report viewer per se, as MacGyver would instruct, nothing should stop us from strapping a rocket on our shoulders and retrofitting it to suit our own personal needs: making our own report preview window for ASP.NET MVC.

When thinking about ASP.NET MVC, the best way to visualize things is to imagine that each Controller Action method is some kind of URL that returns something. Let’s take the bomb apart (because ASP.NET MVC is the bomb) and see if we can retro-fit an action method to return a rendered report.

This is easily done my friends. There is literally only a few lines of code to achieve this, and a little html to get it displayed.

My final result is shown below:


The key here is to use the ContentResult descendant of ActionResult:


  1: // since this is in the HomeController its url is:
  2: // ~/Home/ProductReport
  3: public ActionResult ProductReport()
  4: {
  5:     // Load the pre-fab'ed report
  6:     ProductReport report = new ProductReport();
  7:     report.CreateDocument();
  9:     var options = new HtmlExportOptions();
 11:     // tricky part - export the html into a memory stream
 12:     // but we are pretending to be McG
 13:     using (MemoryStream stream = new MemoryStream())
 14:     {
 15:         report.ExportToHtml(stream, options);
 16:         // move the stream to the beggining
 17:         stream.Seek(0, SeekOrigin.Begin);
 18:         // create a stream reader
 19:         StreamReader reader = new StreamReader(stream);
 20:         // get the actual html
 21:         string html = reader.ReadToEnd();
 23:         // return the actual html
 24:         return new ContentResult
 25:         {
 26:             ContentType = "text/html",
 27:             Content = html
 28:         };
 29:     }
 30: }
The method used to generate the report html is ExportToHtml() that is available on all reports that inherit from XtraReport. The rest is literally playing around with IO.

To get the IFrame to render the report, we need only introduce the following markup:

  1: <iframe id="report" title="Product Report" 
  2:     src="/Home/ProductReport" height="600" width="800"></iframe>

That is it! As always, if there are any questions and/or comments, feel free to get a hold of me!

Seth Juarez
Twitter: @SethJuarez

Free DevExpress Products - Get Your Copy Today

The following free DevExpress product offers remain available. Should you have any questions about the free offers below, please submit a ticket via the DevExpress Support Center at your convenience. We'll be happy to follow-up.
No Comments

Please login or register to post comments.