How to get reports from the Fastreport Web API using AJAX

Source: Internet
Author: User

In the article, "How to use fastreport.net in ASP. NET Web API," We have discussed how to create a Web service to generate a report. Then we will receive a link to the report, now let's see how to get it?? Take the report and display it using an AJAX script.

Let me remind you, our service can return reports exported in one of these formats: PDF, HTML, PNG. We will receive the report in HTML format and use an AJAX script to display it on the Web page.

Let's take a look at the process of creating a WEBAPI application from scratch. First, create an ASP. NET application, WebAPI. Select an empty template and tick options: MVC and Webapi.

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

We continue to create a data model. The Model folder is now empty. Right-click and select "Add", "Class".

Name it as 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;}}}

You need to place the report template and the database file in the App_Data folder. In our example, we put these two statements in: "Simple List.frx" and "Barcode.frx";

Now, in the Controllers folder, add the controller Reportscontroller. It will contain all the logic of the application. We do this using the context menu of the Controllers folder. Select "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 Reportqu  ery {//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") pub  LIC 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 R Eport Reports ReportItem = Reportitems.firstordefault ((p) = P.id = = Id); if (ReportItem! = null) {string reportpath = Hostingenvironment.mappath ("~/app_data/" + reportitem.reportname); string da Tapath = 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 F Astreport Web Mode Config.webmode = true; using (Report report = new report ()) {report. Load (Reportpath); Load the report. Registerdata (DataSet, "NorthWind"); Register the data in the if (query. Parameter = null) {report. Setparametervalue ("Parameter", query. Parameter); Set the value of the parameter in the. The very meaningWe take from the URL}//Both 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 That we does not produce the 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 TThe He data source in the 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-register scripts and styles in the body of the html-page instead of placing them in the title WEBREPORT.W Idth = 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 Httpresponsemessa GE (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 the export FileName = String.Concat (Path.getfilenamewithoutex Tension (Reportpath), ".", query. Format)};//Define The content type for the Browserresult. Content.Headers.ContentType = new Mediatypeheadervalue ("application/" + query. Format); return result; }//Handle Exceptions Catch {return new httpresponsemessage (Httpstatuscode.internalservererror);}} else return new Httpresponsemessage (Httpstatuscode.notfound); } }}

In the Reportscontroller class, we created a report array and two methods. The name and report identifiers are defined in the array. GetAllReports ()method returns a list of available reports. The second method GetReportById (int id, [FromUri] ReportQuery query) returns a report through an identifier. From the query properties, we can get parameter formatting, inline, and parameters. Each of these three decisions: the export format of the report, whether the report will be opened directly in the browser, the value of the parameters passed to the report. Especially interesting is the webReport.GetHtml () method, which allows you to get the HTML view of the report. This is what we use Ajax to display on the page.

In the Web. config file, you need to add two handle handles:

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

In general, we are accustomed to naming the Start Page index. Add the following code to the page:

<! DOCTYPE html>

As you can see from the code, we just load the HTML report file by asking for a service link.

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}); }

In the same folder, locate the RouteConfig.cs file. It can be deleted.

Open the file global.asax. Delete the row:

Routing can now only be done through Webapiconfig.

Run the application, and then click the Download button:

In this way, we received the report.

As can be seen from the above example, it is very simple to use AJAX for report processing.

How to get reports from the Fastreport Web API using AJAX

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.