Dynamic Data Binding at Runtime in RDLC Reports with Bold Reports Report Viewer
Tags: boldreports, databinding, rdlcdynamicbinding, boldreportsembedded
Published: 2024-02-05 06:52:57

RDLC (Report Definition Language Client Side) is a popular reporting format created by Microsoft that is used extensively with classic web platforms and Windows Forms. It is commonly used in conjunction with Microsoft’s Visual Studio (VS) integrated development environment to create reports for applications built on the .NET Framework. VS provides a user-friendly design environment for creating reports and supports various data sources. However, it has not been upgraded to support newer platforms, like Angular. Bold Reports, on the other hand, provides options to integrate with the latest web development platforms, providing a modern interface for integrating business reports into your applications.

In this blog post, we will explore how to use the Bold Reports Report Viewer to display RDLC reports and implement runtime data binding. We will specifically focus on incorporating the Report Viewer into ASP.NET Core, one of the latest web development frameworks that supports dynamic binding.

## **Prerequisites**

Before diving into the development process, make sure your environment is equipped with the following tools:

- [Visual Studio Code](https://code.visualstudio.com/download)
- [NET 7.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/7.0)

## **Creating the ASP.NET Core application**

Let’s start the project by initiating a new ASP.NET Core application. Open your operating system’s command shell and execute the following command, specifying **RDLCDynamicBinding** as the application name:

```
dotnet new mvc --name RDLCDynamicBinding
```

## **Installing essential NuGet packages**

Once your application is generated, it’s time to integrate the required NuGet packages. Navigate to the application’s root folder using the following command:

```
cd RDLCDynamicBinding
```

Now, add the necessary packages to your application with the following commands:

```
dotnet add package BoldReports.AspNet.Core
dotnet add package BoldReports.Net.Core
```

The BoldReports.Net.Core package will automatically install any dependent packages.

## **Incorporating scripts and CSS for the Report Viewer**

To ensure Report Viewer functions seamlessly, reference the required scripts and CSS. Open your application in Visual Studio Code and follow these steps:

1. Navigate to the **Views\Shared** folder and open the **\_Layout.cshtml**  page.
2. Insert the required scripts within the **&lt;head&gt;** tag to complete the setup.

```
<link href="https://cdn.boldreports.com/5.4.20/content/material/bold.reports.all.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!--Render the gauge item. Add this script only if your report contains the gauge report item. -->
<script src="https://cdn.boldreports.com/5.4.20/scripts/common/ej2-base.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/common/ej2-data.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/common/ej2-pdf-export.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/common/ej2-svg-base.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/data-visualization/ej2-lineargauge.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/data-visualization/ej2-circulargauge.min.js"></script>
<!--Render the map item. Add this script only if your report contains the map report item.-->
<script src="https://cdn.boldreports.com/5.4.20/scripts/data-visualization/ej2-maps.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/common/bold.reports.common.min.js"></script>
<script src="https://cdn.boldreports.com/5.4.20/scripts/common/bold.reports.widgets.min.js"></script>
<!--Render the chart item. Add this script only if your report contains the chart report item.-->
<script src="https://cdn.boldreports.com/5.4.20/scripts/data-visualization/ej.chart.min.js"></script>
<!-- Report Viewer component script-->
<script src="https://cdn.boldreports.com/5.4.20/scripts/bold.report-viewer.min.js"></script>
```

## **Configure the script manager**

The code that follows configures a webpage with a main content area, provides an optional section for scripts, and incorporates a script manager (**&lt;bold-script-manager&gt;**) specifically designed for Bold Reports.

Replace the current code within the **&lt;body&gt;** tag with the Bold Script Manager. Make sure the Script Manager is included at the end of the **&lt;body&gt;** element to ensure proper script initialization.

```
<body>
    <div style="min-height: 900px;width: 100%;">
        @RenderBody()
    </div>
    @RenderSection("Scripts", required: false)
    <!-- Bold Reports script manager -->
   <bold-script-manager></bold-script-manager>
</body>
```

## **Setting up the Report Viewer with Tag Helper**

Open the **\_ViewImports.cshtml** file in the **Views** folder and initialize the Report Viewer component with Tag Helper support.

The following code configures the Report Viewer with Tag Helper support in the ASP.NET Core application. It imports the necessary namespace and adds the Bold Reports Tag Helper to enable the use of Report Viewer components with Tag Helper syntax in Razor views.

```
@using BoldReports.TagHelpers
@addTagHelper *, BoldReports.AspNet.Core
```

Now, with these configurations, your project is ready to use the Report Viewer.

## **Add reports to the application**

Next, organize your RDLC reports:

1. Create a folder named **Resources** in the **wwwroot** folder of your application. This will serve as the storage location for your RDLC reports.
2. Add your [RDLC](https://github.com/boldreports/resources/blob/master/blog/sample-applications/rdlc-dynamic-binding/wwwroot/Resources/ProductList.rdlc) reports to the newly created **Resources.**

## **Application overview**

Before adding the Report Viewer to the pages, let’s understand the application that will be demonstrated on this blog. Since this blog focuses on dynamic binding with reports, I am using a product details report. The data for the report will be passed dynamically from the application based on the products selected.

## **Build the page listing product**

The following HTML markup generates a product listing webpage with a styled table. Each row in the table represents a product and displays the product’s ID and name as a clickable link. Clicking on a product link triggers a JavaScript function that redirects the user to a specific product report page. You can copy the code from this GitHub [link](https://github.com/boldreports/resources/blob/master/blog/sample-applications/rdlc-dynamic-binding/Views/Home/Index.cshtml) and paste it into the **index.cshtml** file located in the **Home** folder.

```
<html lang="en">
<head>
....
....
            <tr>
            <td>1</td>
            <td><a href="/Home/ViewReport?productId=1">Baked Chicken and Cheese</a></td>
            </tr>
....   
....  
</body>
</html>
```

## **Add Report Viewer page**

Add the **ViewReport** method that follows in the **HomeController.cs** file and create a corresponding view for this method. The **ViewReport** method is an action in a controller that handles the request to view a report for a specific product. The **productId** parameter is used to identify the product for which the report is being viewed. Pass the **productId** to the **ViewBag** to make it accessible in the corresponding view.

```
public IActionResult ViewReport(int productId)
{
       ViewBag.ProductID = productId;
       // Pass the product data to the view
       return View("ViewReport");
}
```

Initialize the Report Viewer by setting the report service URL, report path, and RDLC as the processing mode. Create the service for the report server URL, which is explained in the next section.

```
@model RDLCDynamicBinding.ProductList
@{
    ViewData["Title"] = "View Report";
}
<!-- RDLC Report Viewer Container -->
<div style="height: 900px; width: 1800px; min-height: 400px;" id="viewer"></div>
<!-- Include the necessary scripts for RDLC Report Viewer -->
... 
<script>
    $(document).ready(function () {
        // Initialize the RDLC Report Viewer with the product data
        $("#viewer").boldReportViewer({
            reportServiceUrl: "/api/ReportViewer",
            reportPath: "Resources/ProductList.rdlc"
        });
});</script>
```

## **Pass the filter value to the API**

Since the Report Viewer is going to display dynamic content based on the product ID, we are sending the product data as custom data to the Report Viewer service through **ajaxBeforeLoad**. This data will later be used in the Report Viewer service API to enable runtime data binding based on the product ID. You can find more details on the custom data process in the Bold Reports [documentation](https://help.boldreports.com/embedded-reporting/aspnet-core-reporting/report-designer/handle-post-actions/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24).

```
<script>
   var productID = "@ViewBag.ProductID";
    $(document).ready(function () {
        // Initialize the RDLC Report Viewer with the product data
        $("#viewer").boldReportViewer({
            reportServiceUrl: "/api/ReportViewer",
            reportPath: "Resources/ProductList.rdlc",
                ajaxBeforeLoad: onAjaxRequest
        });
    });
        function onAjaxRequest(args) {
            args.data = productID;
        }
</script>
```

## **Setting up the web API for ASP.NET Core Report Viewer**

In this section, we will cover how to create the Report Server API for the Report Viewer.

### Create the Report Server API.

Within the **Controller** folder, create a new file named **ReportViewerController.cs** to create the Report Server API. Add the necessary using statement to be used for this controller.

```
using Microsoft.AspNetCore.Mvc;
using BoldReports.Web.ReportViewer;
using Microsoft.Extensions.Caching.Memory;
using System.Collections.Generic;
using System.IO;
using System.Linq;
```

Apply the **Route** and inherit the **ReportViewerController**, **IReportController**.

```
[Route("api/[controller]/[action]")]
public class ReportViewerController : Controller, IReportController
{
}
```

### Implement methods

Provide the necessary variables and methods in the **ReportViewerController** class. The following code shows how to load the report in the Report Viewer:

```
namespace RDLCDynamicBinding.Controllers
{
    [Route("api/[controller]/[action]")]
    public class ReportViewerController : Controller, IReportController
    {
        private IMemoryCache _cache;
        private IWebHostEnvironment _hostingEnvironment;
        public ReportViewerController(IMemoryCache memoryCache, IWebHostEnvironment hostingEnvironment)
        {
            _cache = memoryCache;
            _hostingEnvironment = hostingEnvironment;
        }
        string productID = null;
        [HttpPost]
        public object PostReportAction([FromBody] Dictionary<string, object> jsonResult)
        {
            if (jsonResult != null)
            {
                if (jsonResult.ContainsKey("customData"))
                {
                    //Get client-side custom data and store in local variable.
                    productID = jsonResult["customData"].ToString();
                }
            }
            return ReportHelper.ProcessReport(jsonResult, this, this._cache);
        }
        [HttpPost]
        public object PostFormReportAction()
        {
            return ReportHelper.ProcessReport(null, this, this._cache);
        }
        [NonAction]
        public void OnInitReportOptions(ReportViewerOptions reportOption)
        {
            string basePath = _hostingEnvironment.WebRootPath;
               // Load the RDLC report file
            FileStream inputStream = new FileStream(basePath + @"\Resources\ProductList.rdlc", FileMode.Open, FileAccess.Read);
            MemoryStream reportStream = new MemoryStream();
            inputStream.CopyTo(reportStream);
            reportStream.Position = 0;
            inputStream.Close();
            reportOption.ReportModel.Stream = reportStream;
            // Set the data source directly
            reportOption.ReportModel.DataSources.Add(new BoldReports.Web.ReportDataSource
            {
                Name = "list", // Ensure this matches the dataset name in your RDLC file
                Value = ProductList.GetData().Where(x => x.ProductId.ToString() == productID).ToList()
            });
        }
        [NonAction]
        public void OnReportLoaded(ReportViewerOptions reportOption)
        {
        }
        [ActionName("GetResource")]
        [AcceptVerbs("GET")]
        public object GetResource(ReportResource resource)
        {
            return ReportHelper.GetResource(resource, this, this._cache);
        }
    }
}
```

### RDLC processing

Since we are going to pass the data for the report from the application, we have to set the **ProcessingMode** as **RDLC** with **OnInitReportOptions** , as shown in the following code.

```
[NonAction]
public void OnInitReportOptions(ReportViewerOptions reportOption)
{
   reportOption.ReportModel.ProcessingMode = ProcessingMode.Local;
...
...
}
```

## **Set the data for the Report Viewer**

Next, we need to retrieve the product ID value from the custom data to pass it to the Report Viewer. You can find more information on how to receive data from the Report Viewer client [here](https://help.boldreports.com/embedded-reporting/aspnet-core-reporting/report-viewer/handle-post-actions/#pass-custom-data-in-ajax-request/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24).

```
string productID = null;
[HttpPost]
public object PostReportAction([FromBody] Dictionary<string, object> jsonResult)
   {
       if (jsonResult != null)
       {
          if (jsonResult.ContainsKey("customData"))
          {
             //Get client-side custom data and store in local variable.
             productID = jsonResult["customData"].ToString();
           }
        }
   }
```

Now, I am going to set the data for the Report Viewer using the product information for this report. The data will be shared with the Report Viewer through **ReportModel.DataSources**. The data is dynamically bound to the Report Viewer based on the product ID received from the client side.

```
[NonAction]
public void OnInitReportOptions(ReportViewerOptions reportOption)
{
....
....
     // Set the data source directly
     reportOption.ReportModel.DataSources.Add(new BoldReports.Web.ReportDataSource
     {
         Name = "list", // Ensure this matches the dataset name in your RDLC file
         Value = ProductList.GetData().Where(x => x.ProductId.ToString() == productID).ToList()
     });
}
```

## **Assign data**

To enable dynamic data binding in RDLC reports, it’s essential to dynamically provide data to the application report. Ensure that the **DataSources** are configured with the **OnInitReportOptions** for the Report Viewer.

For the product list report, establish dynamic data binding by creating a class file called **ProductList.cs** in the application’s root folder. You can copy the code from this GitHub [link](https://github.com/boldreports/resources/blob/master/blog/sample-applications/rdlc-dynamic-binding/Models/ProductList.cs) and paste it into the **ProductList** class.

```
using System.Collections;
namespace RDLCDynamicBinding
{
    public class ProductList
    {
.... 
....
    }
}
```

## **Register the license key**

By default, the report generated using the Report Writer will show a license message. To remove this message, we need to register either an online license token or an offline license key.

Click [here](https://help.boldreports.com/embedded-reporting/licensing/online-license-token/#asp-net-core/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24) to learn how to register an online license token. Click [here](https://help.boldreports.com/embedded-reporting/licensing/offline-license-key/#asp-net-core/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24) to learn how to register an offline license key.

## Run the application

With dynamic data binding in place, you are ready to preview the report. Launch your operating system’s command shell and execute the following command:

```
dotnet run
```

Make a note of the generated URL and open it in your preferred browser. This will lead you to a webpage displaying a product list with the product IDs and names.

![Displaying a product list | Reporting Tools](https://www.boldreports.com/wp-content/uploads/2024/01/5-data-view-page-1.png)

Upon clicking any of the product names, the system will retrieve the report for the selected product, as shown in the following figure:

![Retrieved the report for the selected product | Dynamic Data Binding](https://www.boldreports.com/wp-content/uploads/2024/01/5-data-report-page-1.png)

**Note:** The complete sample data for this application is provided [here](https://github.com/boldreports/resources/tree/master/blog/sample-applications/rdlc-dynamic-binding).

## **Conclusion**

Now that you know how to achieve dynamic data binding at runtime in RDLC reports using Bold Reports Report Viewer, your business reports are not only going to inform, they’re also going to impress. To learn more about the ASP.NET Core tools in Bold Reports, browse our [documentation](https://help.boldreports.com/embedded-reporting/aspnet-core-reporting/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24). To experience the many features of Bold Reports, check out our [demos](https://demos.boldreports.com/home/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24).

If you have any questions, please post them in the comments section below. You can also contact us through our [contact page](https://www.boldreports.com/contact/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24), or if you already have an account, you can [log in](https://boldreports.com/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24) to submit your question.

Bold Reports offers a 15-day [free trial ](https://www.boldreports.com/pricing/?utm_source=dev&utm_dev=partner_blog&utm_campaign=dev_dynamicdatabindingatruntime_cy24)with no credit card information required. We welcome you to start a free trial and experience Bold Reports firsthand. Be sure to let us know what you think!

Stay tuned for announcements about new releases by following us on [X](https://twitter.com/boldreportsoffl), [Facebook](https://www.facebook.com/boldreportsofficial/), and [LinkedIn](https://www.linkedin.com/showcase/boldreportsofficial).