How do I get a report from the FastReport Web API using Ajax

[2018-01-16 09:40

In the article “how to use FastReport.Net in ASP.NET Web API,” we discussed how to create a Web service for generating reports. We’ll then receive a link to the report, and now let’s see how to get the report and display it using ajax scripts.

Let me remind you that our service can return reports exported in one of these formats: PDF, HTML, PNG. We will receive the report in HTML format and display it on a Web page using Ajax scripts.

Let’s walk through the process of creating a WebApi application from scratch. First, create an ASP.Net application, WebAPI. Select the empty template and check the options: MVC and WebApi.

In the project reference, add the fastreport.dll library.

Let’s go ahead and create a data model. The Model folder is now empty. Right click and select “Add”, “Class”.

Call it reports.cs. Add two fields: Id and ReportName:

namespace FastReportWebApiDemo.Models { public class Reports { // Report ID public int Id { get; set; } // Report File Name public string ReportName { get; set; }}}Copy the code

You need to place the report template and database files in the App_Data folder. In our example, we put two reports in: “Simple list. FRX” and “barcode. FRX”;

Now, in the Controllers folder, add Controller ReportsController. It will contain all the logic of the application. We do this using the context menu of the Controllers folder. Choose add – > Controller:

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using FastReport; using FastReport.Export.Image; using FastReport.Export.Html; using FastReport.Export.Pdf; using FastReport.Utils; using FastReportWebApiDemo.Models; using System.Web.Hosting; using System.Data; using System.IO; using System.Net.Http.Headers; namespace FastReportWebApiDemo.Controllers { // Transfer class with parameters for requesting a report public class ReportQuery { // Format of resulting report: png, pdf, html public string Format { get; set; } // Value of "Parameter" variable in report public string Parameter { get; set; } // Enable Inline preview in browser (generates "inline" or "attachment") public bool Inline { get; set; } } public class ReportsController : ApiController { //Reports list Reports[] reportItems = new Reports[] { new Reports { Id = 1, ReportName = "Simple List.frx" }, new Reports { Id = 2, ReportName = "Barcode.frx" } }; // Get list of reports public IEnumerable<Reports> GetAllReports() { return reportItems; } // Get report by ID from request public HttpResponseMessage GetReportById(int id, [FromUri] ReportQuery query) { // Find report Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); if (reportItem ! = null) { string reportPath = HostingEnvironment.MapPath("~/App_Data/" + reportItem.ReportName); string dataPath = HostingEnvironment.MapPath("~/App_Data/nwind-employees.xml"); MemoryStream stream = new MemoryStream(); try { using (DataSet dataSet = new DataSet()) { // Fill the data source with the data dataSet.ReadXml(dataPath); // Enable FastReport web mode Config.WebMode = true; using (Report report = new Report()) { report.Load(reportPath); // Load the report report.RegisterData(dataSet, "NorthWind"); // Register the data in the report if (query.Parameter ! = null) { report.SetParameterValue("Parameter", query.Parameter); // Set the value of the parameter in the report. The very meaning we take from the URL } // Two phases of preparation to  exclude the display of any dialogs report.PreparePhase1(); report.PreparePhase2(); if (query.Format == "pdf") { // Export the report to PDF PDFExport pdf = new PDFExport(); // We use the stream to store the report so that we do not produce files report.Export(pdf, stream); } else if (query.Format == "html") { // Export the report to HTML HTMLExport html = new HTMLExport(); html.SinglePage = true; html.Navigator = false; html.EmbedPictures = true; report.Export(html, stream); } else if (query.Format == "png") { // Export the report to PNG using (ImageExport img = new ImageExport()) { img.ImageFormat = ImageExportFormat.Png; img.SeparateFiles = false; img.ResolutionX = 96; img.ResolutionY = 96; report.Export(img, stream); query.Format = "png"; } } else { WebReport webReport = new WebReport(); // Create a report object webReport.Report.Load(reportPath); // Load the report webReport.Report.RegisterData(dataSet, "NorthWind"); // Register the data source in the report if (query.Parameter ! = null) { webReport.Report.SetParameterValue("Parameter", query.Parameter); // Set the value of the report parameter } // inline registration of FastReport javascript webReport.InlineRegistration = true; // Allows you to register scripts and styles in the body of the html-page instead of placing them in the title webReport.Width = Unit.Percentage(100); webReport.Height = Unit.Percentage(100); // get control HtmlString reportHtml = webReport.GetHtml(); // load the report into HTML byte[] streamArray = Encoding.UTF8.GetBytes(reportHtml.ToString()); stream.Write(streamArray, 0, streamArray.Length); // Write the report to the stream } } } // create the resulting variable HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(stream.ToArray()) }; stream.Dispose(); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue(query.Inline ? "inline" : "attachment") { // Set the file extension depending on the type of export FileName = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", query.Format) }; // Define the content type for the browser result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/" + query.Format); return result; } // Handle Exceptions catch { return new HttpResponseMessage(HttpStatusCode.InternalServerError); } } else return new HttpResponseMessage(HttpStatusCode.NotFound); }}}Copy the code

In the ReportsController class, we create a report array and two methods. The name and report identifier are defined in the array. The GetAllReports () method returns a list of available reports. The second method, GetReportById (int ID, [FromUri] ReportQuery Query), returns a report by identifier. From the query properties, we can get the parameter format, inline, and parameters. These three determine, respectively, the format of the report to be exported, whether the report will be opened directly in the browser, and the values of the parameters passed to the report. Of particular interest is the webrePort.gethtml () method, which lets you get an HTML view of the report. This is what we display on the page using Ajax.

In the web. config file, you need to add two processing handles:

The < handlers >... < add name = "ExtensionlessUrlHandler - Integrated - 4.0" path = "*" verb = "*" type = "System. Web. Handlers. TransferRequestHandler" PreCondition = "integratedMode, runtimeVersionv4.0" / > < add name = "FastReportHandler" path = "FastReport. Export. Axd" verb = "*" Type = "FastReport. Web. Handlers. WebExport" / >... </handlers>Copy the code

Now add the page. Right-click on the project and select Add-> HTML Page.

We usually name the start page Index. Add the following code to the page:

<! DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> <script type="text/javascript" SRC = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" > < / script > < / head > < body > < script type="text/javascript" language="javascript"> function call() { var msg = $('#formx').serialize(); $.ajax({ type: 'GET',// Type url: 'http://localhost:58005/api/reports/1', // We receive a file from Rest service cache: false,// Caching timeout: 30000,// Timeout data: msg, success: function (data) {// The function will work if the data is successfully received $('#results').html(data); // We display the data in the form }, beforeSend: function (data) {// The function is activated during the waiting period of data $('#results').html('<p> Waiting for data... </p>'); }, dataType: "html", // Data type error: function (data) {// Function will work if an error occurs $('#results').html('<p> Failed to load report</p>'); }}); } </script> <form method="GET" id="formx" action="javascript:void(null);" Onsubmit = "call ()" > < input value = "З а f р з и т ь" type = "submit" > < / form > < div id = "results" typeof = "submit" > < / div > <! -- Here the result will be displayed--> </body> </html>Copy the code

As you can see from the code, we simply load the HTML report file from the service link request.

Open the file WebApiConfig. Cs from the folder App_Start. Add a MapHttpRoute to the Index page:

public static void Register(HttpConfiguration config)
 {
 // Web API configuration and services
 // Web API routes
 config.MapHttpAttributeRoutes();
 config.Routes.MapHttpRoute(
 name: "Index",
 routeTemplate: "{id}.html",
 defaults: new { id = "index" }
 );
 
 config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );
 }
Copy the code

In the same folder, find the RouteConfig. Cs file. It can be deleted.

Open the file global.asax. Delete the line:

RouteConfig.RegisterRoutes(RouteTable.Routes); Copy the code

Now routing can only be done through WebApiConfig.

Run the application, and then click the Download button:

Just like that, we received the statement.

As is clear from the above example, using Ajax for report processing is very simple.


Product introduction | download the trial | | | online customer service, contact Elyn preferential activities

 

Recommended reading
  • A few tips to help you create reports faster
  • How do I connect a MySQL database to a report
  • How do I create interactive Web reports in an MVC project
  • How do I use reports when developing MVC applications
  • How to download a report as an Excel document in MVC
  • FastReport.Net v2018.1 update has been released! (With download resources)