Integrating the Report Viewer into the .NET 7 Blazor Server Application
In this blog post, we'll guide you through the process of integrating the Report Viewer into your .NET 7 Blazor Server application. Reporting plays a pivotal role in numerous applications, and having a user-friendly Report Viewer can greatly enhance the user experience.
In this article, we'll show you how to seamlessly incorporate the Report Viewer, allowing your users to access their reports.
Prerequisites
Before getting started, ensure your development environment includes the following:
Create a Blazor Server Application
Open the command prompt, navigate to your desired project directory, and run the following command to create a new Blazor Server application.
dotnet new blazorserver --name BlazorReportViewer
A new Blazor server application named BlazorReportViewer is created.
Install the NuGet Packages
We need to install the necessary NuGet packages in the application, which will be used for processing the RDL reports:
Navigate to the root directory of the Blazor Server project.
cd BlazorReportViewer
Install the Net.Core package, which is used to create a Web API service for processing reports by running the following command.
dotnet add package BoldReports.Net.Core
Install the AspNetCore.Mvc.NewtonsoftJson package, which provides ASP.NET Core MVC features that use Newtonsoft.Json. Ensure the package version is higher than 3.1.2. Run this command to install the package:
dotnet add package Microsoft.AspNetCore.Mvc.NewtonsoftJson
Create Web API for Report Processing
In this section, we are going to create a Web API controller that will be used to process the provided RDL report:
Open your Blazor Server application in Visual Studio Code.
In the Explorer pane, right-click on the Data folder and select New File.
Provide the file name ReportViewerController.cs.
This will create a new file called ReportsViewerController.cs in the Data folder.
Next, add the using statements in the ReportViewerController.cs file to import necessary libraries and define the namespace for the controller class. The libraries enable our Blazor Server application to render, process, and interact with RDL reports, support Web API creation, and enhance controller-related capabilities for the integration of the Report Viewer.
using BoldReports.Web.ReportViewer; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory
Add the namespace that allows you to organize and group code together to avoid naming conflicts.
namespace BlazorReportViewer.Data { }
Next, add the route template that specifies that the incoming HTTP requests will be mapped to the controller and action specified in the template, with the optional id.
[Route("api/{controller}/{action}/{id?}")]
Next, create a public class named ReportViewerController that inherits the ControllerBase, and IReportController.
public class ReportViewerController : ControllerBase, IReportController {}
The IReportController interface has a declaration of action methods required in the Web API controller for processing reports and handling resource requests.
Use the IHostingEnvironment interface by importing the Microsoft.AspNetCore.Hosting namespace and injecting it through dependency injection, to read the report file from the application.
private IMemoryCache _cache;
private IWebHostEnvironment _hostingEnvironment;
public ReportViewerController(IMemoryCache cache, IWebHostEnvironment hostingEnvironment)
{
_cache = cache;
_hostingEnvironment = hostingEnvironment;
}
- Then add the following methods.
[ActionName("GetResource")]
[AcceptVerbs("GET")]
public object GetResource(ReportResource resource)
{
return ReportHelper.GetResource(resource, this, _cache);
}
[NonAction]
public void OnInitReportOptions(ReportViewerOptions reportOption)
{
string basePath = Path.Combine(_hostingEnvironment.WebRootPath, "Resources");
string reportPath = Path.Combine(basePath, reportOption.ReportModel.ReportPath);
FileStream fileStream = new FileStream(reportPath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
MemoryStream reportStream = new MemoryStream();
fileStream.CopyTo(reportStream);
reportStream.Position = 0;
fileStream.Close();
reportOption.ReportModel.Stream = reportStream;
}
[NonAction]
public void OnReportLoaded(ReportViewerOptions reportOption)
{
}
[HttpPost]
public object PostFormReportAction()
{
return ReportHelper.ProcessReport(null, this, _cache);
}
[HttpPost]
public object PostReportAction([FromBody] Dictionary<string,object> jsonArray)
{
return ReportHelper.ProcessReport(jsonArray, this, _cache);
}
Methods | Description |
GetResource | This action gets the images used in the report from the server at the time of preview in the Designer. |
OnlnitReportOptions | This invokes from a ReportHelper when the report is about to be processed at the time of preview. Before the report loads, you can customize CSV delimiters like in the following. |
OnReportLoaded | This invokes from a ReportHelper when the report and subreport start loading for report rendering. |
PostReportAction | This action processes the report request on the server side and returns the processed reporting result to the client side. |
PostFormReportAction | This action saves the exported report to the client. |
The ReportHelperclass contains helper methods to process the request on the server side and return the response to the Report Viewer control.
The GetResource method returns the report resource to the requested key.
The ProcessReport method processes the report request and returns the result.
Initialize the Report Viewer
To initialize the Report Viewer with basic parameters, you need to integrate the Bold Reports JavaScript controls by creating an interop file:
First, create a BoldReportViewerOptions.cs class in the Data folder with the following code to hold RDL report-rendering properties.
namespace BlazorReportViewer.Data { public class BoldReportViewerOptions { public string? ReportPath { get; set; } public string? ReportServiceUrl { get; set; } } }
Next, create a script folder inside the wwwroot folder.
Then create a boldreports-interop.js file inside the wwwroot/scripts folder and add the following code snippet to invoke the Bold Report Viewer JavaScript control.
//Interop file to render the Bold Report Viewer component with Properties window.BoldReports = { RenderViewer: function (elementID, reportViewerOptions) { $("#" + elementID).boldReportViewer ({ reportPath: reportViewerOptions.reportPath, reportServiceUrl: reportViewerOptions.reportServiceUrl }) } }
Add an RDL Report to the Blazor Server Application
Create a Resources folder in the wwwroot folder in your application to store the RDL reports.
Download the sales-order-detail.rdl file from here. For more sample reports, refer to the samples and demos section.
Extract the compressed file and paste the sales-order-detail.rdl file in the Resources folder.
Reference the Scripts and Theme Related to Blazor Report Viewer
Next, reference the following CDN links along with the boldreports-interop.js file in the head section of Pages/_Host.cshtml to use the JavaScript reporting controls in your Blazor application.
<link href="https://cdn.boldreports.com/5.2.26/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>
<!--Used to render the gauge item. Add this script only if your report contains the gauge report item. -->
<script src="https://cdn.boldreports.com/5.2.26/scripts/common/ej2-base.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/common/ej2-data.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/common/ej2-pdf-export.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/common/ej2-svg-base.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/data-visualization/ej2-lineargauge.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/data-visualization/ej2-circulargauge.min.js"></script>
<!--Used to render the map item. Add this script only if your report contains the map report item.-->
<script src="https://cdn.boldreports.com/5.2.26/scripts/data-visualization/ej2-maps.min.js"></script>
<!-- Report Viewer component script-->
<script src="https://cdn.boldreports.com/5.2.26/scripts/common/bold.reports.common.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/common/bold.reports.widgets.min.js"></script>
<!--Used to render the chart item. Add this script only if your report contains the chart report item.-->
<script src="https://cdn.boldreports.com/5.2.26/scripts/data-visualization/ej.chart.min.js"></script>
<script src="https://cdn.boldreports.com/5.2.26/scripts/bold.report-viewer.min.js"></script>
<!-- Blazor interop file -->
<script src="~/scripts/boldreports-interop.js"></script>
Render Blazor Report Viewer in a Razor Page
To render the Blazor Report Viewer in a Razor page, you need to use the JavaScript interop. To do so, open the Pages/Index.razor file and paste the following code.
@page "/"
@using Microsoft.JSInterop
@using Microsoft.AspNetCore.Components
@inject IJSRuntime JSRuntime
@using BlazorReportViewer.Data;
<div id="report-viewer" style="width: 100%;height: 950px"></div>
@code {
BoldReportViewerOptions viewerOptions = new BoldReportViewerOptions();
public async void RenderReportViewer()
{
viewerOptions.ReportPath = "sales-order-detail.rdl";
viewerOptions.ReportServiceUrl = "/api/ReportViewer";
await JSRuntime.InvokeVoidAsync("BoldReports.RenderViewer", "report-viewer", viewerOptions);
}
protected override void OnAfterRender(bool firstRender)
{
RenderReportViewer();
}
}
The code has the following methods to render the Blazor Report Viewer.
Methods | Description |
RenderReportViewer | Renders the Report Viewer components in a Blazor page. |
OnAfterRender | Initializes the Report Viewer by calling the method RenderReportViewer that we created. |
Register the Valid License Token
To avoid receiving an invalid licence error message when previewing the report, you need to register a license token. In this setup, we are using the online license token.
You can generate this license token from the accounts section of the Bold Reports site.
In the application, we open the program.cs file and enter the code snippet to register the licence token.
// Register your Bold license token here
Bold.Licensing.BoldLicenseProvider.RegisterLicense("YOUR ONLINE LICENSE TOKEN");
Click here to learn how to register a license token using online license tokens.
Run the Application
To run your Blazor application and view the report, open the Command prompt, and navigate to the root directory of your Blazor Server project.
Run your Blazor application by executing the following command.
dotnet run
Once your application is running, copy the provided URL to your web browser's address bar and press Enter.
Your Blazor application will load, and the report will be rendered and displayed within the Report Viewer.
Conclusion
This blog post covered the step-by-step process of integrating the web Report Viewer into a .NET 7 Blazor Server application. We hope you found this guide helpful. To learn more about the Report Viewer for Blazor and using report items in it, look through our documentation site. You can also check out our demo samples to experience the features live.
If you have any questions, please post them in the comments section. You can also contact us through our contact page or log in if you already have an account. If not, you are welcome to start a 15-day free trial to experience Bold Reports for yourself without any credit card information required. Stay tuned for announcements about new releases by following us on our Twitter, Facebook, LinkedIn, Pinterest, and Instagram pages.
Subscribe to my newsletter
Read articles from Bold Reports Team directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by