Rendering an RDLC directly to the Response stream in ASP.NET MVC - Raj Kaimal

Rendering an RDLC directly to the Response stream in ASP.NET MVC

The following post shows you how to render an RDLC (Client Report Definition File) in a MVC project. For this tutorial, I am using VS 2008 with MVC 2 Beta. I will also be using the priceless Northwind database and the report will contain a list of customers in the Northwind database.

A sample project zip file is provided at the bottom of this post.

We start off by creating an ASP.NET MVC 2 Empty Web Application.

image 

Add a new ADO.NET entity model and choose the option to “Generate from the database”.

 image
image 
Choose the connection string to use

image

Choose the database objects (Customers for our scenario) and hit finish. We see that a new entity data model has been created in the Models directory.

image 
Create a folder called Content and a subfolder called Reports and add an RDLC into this folder. I hate working with Datasets and hence will not be using the “Report Wizard”. We choose the “Report” template instead. 

image

Create a method that returns all the customers in the database through a Customer partial class and add this in the Model folder.

image

using System;
using System.Linq;
using System.Collections.Generic;
 
namespace RDLCRendering.Models
{
    public partial class Customers
    {
        public static List<Customers> GetAllCustomers() {
            var entities = new NorthwindEntities();
            var x = from c in entities.Customers
                    select c;
            return x.ToList();
        }
    }
}

Open  the RDLC. Your UI should look like so (If you don’t see “Website Data Sources”, click on Data –> Show Data Sources):

image

Design your report by adding a table from the toolbox and dragging and dropping fields from the Website Data Sources (reference).

image 

We will now construct our basic MVC web application. The app will have a home screen and a link to view the PDF report of Northwind customers.
Lets start by adding a Home controller

image 

We add the following code in our HomeController class

namespace RDLCRendering.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            string welcomeMessage = "Welcome to Northwind Traders. Enjoy the view!";
            return View((object)welcomeMessage);
        }
    }
}

Right click on the "Index()” method and select “Add View”.

image

Open the Index view and add code to display the string returned and also add a link for the report in the view like so:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<string>" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Index</title>
</head>
<body>
    <div>
        <h2>
            <%=Html.Encode(Model) %></h2>
            
            <%=Html.ActionLink("Customers Report (PDF)", "DetailsReport", "Customers") %>
    </div>
</body>
</html>

 
Run the application. You should see a UI similar to the one below:
 
image
If you click on the link you will get a “The resource cannot be found.” error. This is because our Html.Action link refers to a method called “DetailsReport” in a CustomersController which does not exist yet.
Note that we are using the ActionLink overload(linkText, actionName, controllerName).
 
First add a reference to Microsoft.ReportViewer.WebForms in your project.
image
Add a CustomerController class and add a DetailsReport method like so:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Microsoft.Reporting.WebForms;
using RDLCRendering.Models;
 
namespace RDLCRendering.Controllers
{
    public class CustomersController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
 
        public ActionResult DetailsReport()
        {
            LocalReport localReport = new LocalReport();
            localReport.ReportPath = Server.MapPath("~/Content/Reports/CustomerReport.rdlc");
            ReportDataSource reportDataSource = new ReportDataSource("Customers", Customers.GetAllCustomers());
 
            localReport.DataSources.Add(reportDataSource);
            string reportType = "PDF";
            string mimeType;
            string encoding;
            string fileNameExtension;
 
            //The DeviceInfo settings should be changed based on the reportType
            //http://msdn2.microsoft.com/en-us/library/ms155397.aspx
            string deviceInfo =
            "<DeviceInfo>" +
            "  <OutputFormat>PDF</OutputFormat>" +
            "  <PageWidth>8.5in</PageWidth>" +
            "  <PageHeight>11in</PageHeight>" +
            "  <MarginTop>0.5in</MarginTop>" +
            "  <MarginLeft>1in</MarginLeft>" +
            "  <MarginRight>1in</MarginRight>" +
            "  <MarginBottom>0.5in</MarginBottom>" +
            "</DeviceInfo>";
 
            Warning[] warnings;
            string[] streams;
            byte[] renderedBytes;
 
            //Render the report
            renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);
            //Response.AddHeader("content-disposition", "attachment; filename=NorthWindCustomers." + fileNameExtension);
            return File(renderedBytes, mimeType);
        }
    }
}

This method will create an instance of the LocalReport class, set the Report path property, add a ReportDataSource which points to the GetAllCustomers method we defined earlier, set the report output type and page dimensions, calls the render method and invokes the File method on the Controller class. This method return a FileContentResult which sends the contents of a binary file to the response stream.
Run the page and click on the link. You should see the PDF report like so:
 
image
If you wish to prompt the user to download the PDF file, uncomment the “content-disposition” line and recompile.
 
 
Related Posts
Published Wednesday, November 25, 2009 1:21 AM by rajbk

Comments

# re: Rendering an RDLC directly to the Response stream in ASP.NET MVC

Hello Raj. Thanks for the post. I have problem when implement this. first time its working but after that, it show me the error :

"An error occurred during local report processing" ,

at these lines :

renderedBytes = localReport.Render(

               reportType,

               deviceInfo,

               out mimeType,

               out encoding,

               out fileNameExtension,

               out streams,

               out warnings);

wpuld you please to help me how to fix it ? thank you very much

Fikri

Tuesday, February 9, 2010 2:56 AM by fikri.salam

# re: Rendering an RDLC directly to the Response stream in ASP.NET MVC

Thanks for blog, It's good, so i think we need more something to develop professional website. I confused for create report in MVC

Monday, July 5, 2010 4:55 AM by TamDuong

# re: Rendering an RDLC directly to the Response stream in ASP.NET MVC

I've tried this in MVC 2 but get a security exception about partially trusted code.  I have tried adding [assembly: AllowPartiallyTrustedCallers] but that has not worked.  I've searched online for answers but haven't found anything that works.

Mark

Thursday, July 8, 2010 12:10 PM by mimeyers

# re: Rendering an RDLC directly to the Response stream in ASP.NET MVC

I'm using Visual Studio 2010 Ultimate, and cannot find the option "Website Data Sources"

where should it be?

Wednesday, November 3, 2010 5:14 PM by Andrea