Passing Parameters to HTML5 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
-
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 thereportSource
property:public class ReportSourceModel { public string Report { get; set; } public Dictionary<string, object> Parameters { get; set; } }
-
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 = "Product Line Sales.trdp", Parameters = new Dictionary<string, object>() }; reportSourceModel.Parameters.Add("ProductCategory", "Clothing"); reportSourceModel.Parameters.Add("ProductSubcategory", new string[] { "Caps", "Gloves", "Vests" }); return View(reportSourceModel); } }
-
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 theHtml.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.