New to Telerik Reporting? Download free 30-day trial

Pass parameters to the HTML5 Report Viewer from the Model of a View

Environment

Product Progress® Telerik® Reporting
Project Type ASP.NET Core

Description

When working with the HTML Report Viewer jQuery widget, passing parameters to it from the model of the view can be a bit tricky sometimes. This is due to the serialization and encoding of the model properties. The following article describes a general approach that can be used to both achieve the above, and reduce the amount of JSON one needs to type to initialize the viewer.

Solution

  1. Since the parameters dictionary is a child element of the reportSource property, as shown in the HTML5 Report Viewer API Reference, we will create a custom model that represents the reportSource property.

    public class ReportSourceModel
    {
    public string Report { get; set; }
    public Dictionary<string, object> Parameters { get; set; }
    }
    
  2. Then we can create an instance of this model and conveniently pass all the necessary parameters in our controller

    public class HomeController : Controller
    {
    public IActionResult Index()
    {
        var reportSourceModel = new ReportSourceModel()
        {
            Report = "Barcodes Report.trdp",
            Parameters = new Dictionary<string, object>()
        };
        reportSourceModel.Parameters.Add("MyParameter1", DateTime.Now);
        reportSourceModel.Parameters.Add("MyParameter2", 42);
    
        return View(reportSourceModel);
    }
    }
    
  3. Once this is done, it is important that the value we provide to the Report Viewer widget is serialized to JSON, and any HTML encoding is removed. We can use the Json.Serialize() and the Html.Raw() methods respectively to accomplish this.

    @using Demo.Models
    @model ReportSourceModel
    
    <div id="reportViewer1">
        loading...
    </div>
    
    @{
        var reportSource = Html.Raw(Json.Serialize(Model));
    }
    
    <script type="text/javascript">
    
        $("#reportViewer1")
            .telerik_ReportViewer({
                id: "reportviewer1",
                serviceUrl: "/api/reports/",
                reportSource: @reportSource
            });
        });
    </script>
    

    Demo Project

You can find a sample project that implements the above in the following GitHub repo.

See Also

In this article