.Net

Eat, sleep, code.

Magical one page telerik reporting viewer

C# Reporting
Magical one page telerik reporting viewer

In an effort to simplify a project that used Telerik’s Reporting Engine, I wanted to create a single View that listed the available reports and a single View to hold the HTML Report Viewer. In the middle of the project a new requirement was added; you know how that goes. Some reports needed to be able to have querystring parameters come from a related View. This is how I did it. Behold the magic.

First I built my View to list the reports. Each report had a link like this:

@Html.ActionLink("Click Me", "Report", 
    new { title = "Report Title", path = "Namespace.Path.To.Report" }, 
    new { target = "_blank", @class = "btn btn-primary" })

You can get the Namespace path from the code behind file of the report.

Set up an ActionResult like this:

public ActionResult Report(string path, string title)

{

    ViewBag.ReportPath = path + ", ProjectNS";

    ViewBag.Title = title;

    return View();

}

ProjectNS should be your root Namespace. 

And the matching View:

@using Telerik.Reporting

@using Telerik.ReportViewer.Mvc

 

@{
    Layout = "~/Views/Shared/_ReportsLayout.cshtml";
}

 

@functions {
    private ReportSource GenSource()
    {
        var typeReportSource = new TypeReportSource {TypeName = ViewBag.ReportPath};

        if (Request["path"] == "Namespace.Path.To.Report" && !string.IsNullOrEmpty(Request["id"]))
        {
            typeReportSource.Parameters.Add(new Parameter("Id", Request["id"]));
        }
        return typeReportSource;
    }
}
 
@(Html.TelerikReporting().ReportViewer()
        .Id("reportViewer1")
        .ServiceUrl("/api/reports/")
        .TemplateUrl("/ReportViewer/templates/telerikReportViewerTemplate.html")
                    .ReportSource(GenSource())
        .ViewMode(ViewModes.INTERACTIVE)
        .ScaleMode(ScaleModes.SPECIFIC)
        .Scale(1.0)
        .PersistSession(false)
)

What’s cool about this code block is that you can craft Querystring parameters to pass in values to the report from another page. Like so:

/Report?title=Title&path=Namespace.Path.To.Report&id=42&active=True

Not only will the Report view load the correct report, it will also load in these default values:

 

comments powered by Disqus

FOLLOW ME!

© Copyright 2018