Search results
Suggest a FeaturePDF

Add Web Report Designer to an ASP.NET MVC application

This section explains the steps required to add Web Report Designer version higher than v5.2.xx to an ASP.NET MVC application.

Prerequisites

To get started with ASP.NET MVC 5 application, ensure the following software to be installed on the machine.

  • .Net Framework 4.5 and above.
  • ASP.NET MVC 5

Create ASP.NET MVC 5 web application

  1. Open Visual Studio 2017, click the File menu, go to New, and then select Project.
  2. Go to Installed > Visual C# > Web, and then select the required .NET Framework in the drop-down.
  3. Select ASP.NET Web Application (.NET Framework), change the application name, and then click OK. Project Creation Wizard
  4. Then choose the MVC in the template and enable the Web API option in the Add folders and core references for: section. Asp.Net MVC5 web application template

Add Assembly References

  1. Right-click the project/solution in the Solution Explorer tab, and choose Manage NuGet Packages…. Alternatively, select the Tools > NuGet Package Manager > Manage NuGet Packages for Solution menu command.

    Refer to the NuGet Packages to learn more details about installing and configuring Report Designer NuGet packages.

  2. Search for BoldReports.Web, BoldReports.Mvc5, and BoldReports.JavaScript NuGet packages, and install them in your MVC application.

    Package Purpose
    BoldReports.Web Used to create Web API service for processing the reports.
    BoldReports.Mvc5 Contains tag helpers to create client-side web Report Designer control.
    BoldReports.JavaScript Contains Report Designer scripts and style sheets.

Registering namespaces within Web.config

Open ~/Views/Web.config file and add the BoldReports.Mvc namespace under the namespaces tag.

<namespaces>
    <add namespace="BoldReports.Mvc"/>
</namespaces>

Disable unobtrusive mode

Set the UnobtrusiveJavaScriptEnabled to false in Web.config file of root directory as shown in the below image.

Disable unobtrusive mode

Refer Scripts and Styles

Add the listed references in the same order as given below. You can replace the following code in the \Views\Shared\_Layout.cshtml page.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Styles.Render("~/Content/bold-reports/v2.0/tailwind-light/bold.report-designer.min.css")
    @Styles.Render("~/Scripts/CodeMirror/lib/codemirror.css")
    @Styles.Render("~/Scripts/CodeMirror/addon/hint/show-hint.css")
    @Scripts.Render("~/bundles/modernizr")

</head>
<body>
    <div style="height: 600px;width: 100%;">
        @RenderBody()
    </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @Scripts.Render("~/Scripts/CodeMirror/lib/codemirror.js")
    @Scripts.Render("~/Scripts/CodeMirror/addon/hint/show-hint.js")
    @Scripts.Render("~/Scripts/CodeMirror/addon/hint/sql-hint.js")
    @Scripts.Render("~/Scripts/CodeMirror/mode/sql/sql.js")
    @Scripts.Render("~/Scripts/CodeMirror/mode/vb/vb.js")

    <!-- Report Designer component dependent scripts -->
    @Scripts.Render("~/Scripts/bold-reports/v2.0/common/bold.reports.common.min.js")
    @Scripts.Render("~/Scripts/bold-reports/v2.0/common/bold.reports.widgets.min.js")

    <!-- Report Viewer and Designer component scripts -->
    @Scripts.Render("~/Scripts/bold-reports/v2.0/bold.report-viewer.min.js")
    @Scripts.Render("~/Scripts/bold-reports/v2.0/bold.report-designer.min.js")
    @RenderSection("scripts", required: false)
</body>
</html>

Refer to the Dependencies to learn more details about web Report Designer dependent scripts and style sheets links.

Configure Script Manager

Open the ~/Views/Shared/_Layout.cshtml page and add the Script Manager at the end of <body> element as in the following code sample.

<body>
    ....
    ....
    <!-- Bold Reporting ScriptManager -->
    @Html.Bold().ScriptManager()
</body>

The main reason for referring the Script manager in _Layout file is that, it can be referred as common by all the View files present within your application.

Add Control in View page

Using Bold() tag add the Bold Report Designer component in any web page (cshtml) of your application in the ~/Views folder.

    @(Html.Bold().ReportDesigner("designer"))

Add API controller

The MVC ReportDesigner uses WebApi services to process the report file and process the request from control.

  1. Right-Click on the project and select Add then click New Folder and provide the folder name.
  2. Right-Click on the newly created folder and select Add then click New Item.
  3. Select Web API Controller Class from the listed templates and name the controller as ReportingAPIController.cs. Provide controller name
  4. Click Add. Click Add

While adding Web API Controller class, name it with the suffix Controller that is mandatory.

Configure Web API

The interface IReportDesignerController has the declaration of action methods that are defined in Web API Controller to retrieve data, save, edit and browse reports from the server. The IReportDesignerController has the following action methods declaration.

Methods Description
PostDesignerAction Action (HttpPost) method for posting the request for designer actions.
UploadReportAction Action (HttpPost) method for posted file actions.
SetData Writes the resource into storage location.
GetData Reads the resource from storage location.
GetImage Action (HttpGet) method for getting resource of images in the report.
PostReportAction Action (HttpPost) method for posting the request for report process.
GetResource Action (HttpGet) method for getting resource for report.
OnInitReportOptions Report initialization method that occurs when the report is about to be processed.
OnReportLoaded Report loaded method that occurs when the report and sub report start loading.

ReportDesignerHelper

The class ReportDesignerHelper contains helper methods that help to process Post or Get request from the web Report Designer control and returns the response to the web Report Designer control. It has the following methods.

Methods Description
GetResource Returns the report resource for the requested key.
ProcessReport Processes the report request and returns the result.

ReportHelper

The class ReportHelper contains helper methods that help process Post or Get request for report preview action and returns the response to the web Report Designer. It has the following methods.

Methods Description
GetResource Returns the report resource for the requested key.
ProcessReport Processes the report request and returns the result.

Open ReportingAPIController.cs file and replace the following code example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BoldReports.Web;
using BoldReports.Web.ReportViewer;
using BoldReports.Web.ReportDesigner;
using System.IO;
using System.Reflection;
using System.Web;

namespace ReportDesignerSample.Api
{
    public class ReportingAPIController : ApiController, IReportDesignerController
    {
        /// <summary>
        /// Get the path of specific file
        /// </summary>
        /// <param name="itemName">Name of the file to get the full path</param>
        /// <param name="key">The unique key for report designer</param>
        /// <returns>Returns the full path of file</returns>
        [NonAction]
        private string GetFilePath(string itemName, string key)
        {
            string dirPath = Path.Combine(HttpContext.Current.Server.MapPath("~/")+ "Cache", key);

            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            return Path.Combine(dirPath, itemName);
        }

        /// <summary>
        /// Action (HttpGet) method for getting resource of images in the report.
        /// </summary>
        /// <param name="key">The unique key for request identification.</param>
        /// <param name="image">The name of requested image.</param>
        /// <returns>Returns the image as HttpResponseMessage content.</returns>
        [System.Web.Http.ActionName("GetImage")]
        [AcceptVerbs("GET")]
        public object GetImage(string key, string image)
        {
            return ReportDesignerHelper.GetImage(key, image, this);
        }

        /// <summary>
        /// Action (HttpPost) method for posting the request for designer actions.
        /// </summary>
        /// <param name="jsonData">A collection of keys and values to process the designer request.</param>
        /// <returns>Json result for the current request.</returns>
        public object PostDesignerAction(Dictionary<string, object> jsonData)
        {
            //Processes the designer request and returns the result.
            return ReportDesignerHelper.ProcessDesigner(jsonData, this, null);
        }

        /// <summary>
        /// Sets the resource into storage location.
        /// </summary>
        /// <param name="key">The unique key for request identification.</param>
        /// <param name="itemId">The unique key to get the required resource.</param>
        /// <param name="itemData">Contains the resource data.</param>
        /// <param name="errorMessage">Returns the error message, if the write action is failed.</param>
        /// <returns>Returns true, if resource is successfully written into storage location.</returns>
        [NonAction]
        public bool SetData(string key, string itemId, ItemInfo itemData, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (itemData.Data != null)
            {
                File.WriteAllBytes(this.GetFilePath(itemId, key), itemData.Data);
            }
            else if (itemData.PostedFile != null)
            {
                var fileName = itemId;
                if (string.IsNullOrEmpty(itemId))
                {
                    fileName = Path.GetFileName(itemData.PostedFile.FileName);
                }
                itemData.PostedFile.SaveAs(this.GetFilePath(fileName, key));
            }
            return true;
        }

        /// <summary>
        /// Gets the resource from storage location.
        /// </summary>
        /// <param name="key">The unique key for request identification.</param>
        /// <param name="itemId">The unique key to get the required resource.</param>
        ///  <returns>Returns the resource data and error message.</returns>
        [NonAction]
        public ResourceInfo GetData(string key, string itemId)
        {
            var resource = new ResourceInfo();
            try
            {
                var filePath = this.GetFilePath(itemId, key);
                if (itemId.Equals(Path.GetFileName(filePath), StringComparison.InvariantCultureIgnoreCase) && File.Exists(filePath))
                {
                    resource.Data = File.ReadAllBytes(filePath);
                }
                else
                {
                    resource.ErrorMessage = "File not found from the specified path";
                }
            }
            catch (Exception ex)
            {
                resource.ErrorMessage = ex.Message;
            }

            return resource;
        }

        /// <summary>
        /// Action (HttpPost) method for posted or uploaded file actions.
        /// </summary>
        public void UploadReportAction()
        {
            //Processes the designer file upload request's.
            ReportDesignerHelper.ProcessDesigner(null, this, System.Web.HttpContext.Current.Request.Files[0]);
        }

        /// <summary>
        /// Send a GET request and returns the requested resource for a report.
        /// </summary>
        /// <param name="key">The unique key to get the desired resource.</param>
        /// <param name="resourcetype">The type of the requested resource.</param>
        /// <param name="isPrint">If set to <see langword="true"/>, then the resource is generated for printing.</param>
        /// <returns> Resource object for the given key</returns>
        [System.Web.Http.ActionName("GetResource")]
        [AcceptVerbs("GET")]
        public object GetResource(string key, string resourcetype, bool isPrint)
        {
            //Returns the report resource for the requested key.
            return ReportHelper.GetResource(key, resourcetype, isPrint);
        }

        /// <summary>
        /// Report Initialization method that is triggered when report begin processed.
        /// </summary>
        /// <param name="reportOptions">The ReportViewer options.</param>
        [NonAction]
        public void OnInitReportOptions(ReportViewerOptions reportOption)
        {
            //You can update report options here
        }

        /// <summary>
        /// Report loaded method that is triggered when report and sub report begins to be loaded.
        /// </summary>
        /// <param name="reportOptions">The ReportViewer options.</param>
        [NonAction]
        public void OnReportLoaded(ReportViewerOptions reportOption)
        {
            //You can update report options here
        }

        /// <summary>
        /// Action (HttpPost) method for posting the request for report process.
        /// </summary>
        /// <param name="jsonData">The JSON data posted for processing report.</param>
        /// <returns>The object data.</returns>
        public object PostReportAction(Dictionary<string, object> jsonData)
        {
            //Processes the report request and returns the result.
            return ReportHelper.ProcessReport(jsonData, this as IReportController);
        }
    }
}

Add routing information

  1. Open the WebApiConfig.cs file from App_Start folder of your application.

  2. Modify the routeTemplate in Register event to include the {action} parameter in the URI as follows.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Http;
    
    namespace ReportDesignerSample
    {
        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                // Web API configuration and services
    
                // Web API routes
                config.MapHttpAttributeRoutes();
    
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    }

Set the service URL

To browse, open and save the reports in the application, set the WebAPI controller name to the ServiceUrl property of the web Report Designer. You can replace the following code in the cshtml page.

@(Html.Bold().ReportDesigner("designer").ServiceUrl(Url.Content("https://demos.boldreports.com/services/api/ReportingAPI")))

Run the Application

On running the application, web Report Designer will be rendered like below.

Web Report Designer

Note: You can refer to our feature tour page for the ASP.NET MVC Report Designer to see its innovative features. Additionally, you can view our ASP.NET MVC Report Designer examples which demonstrate the rendering of SSRS RDLC and RDL reports.