How to get a report from FastReport WebApi using ajax
In the article "How to use FastReport.Net in the ASP.NET Web API" we have already discussed how to create a web service for generating reports. Then we received reports on the link, now we'll look at how to get the report and display it using ajax script.
Let me remind you that our service can return a report in one of the export formats: PDF, HTML, png. We will receive the report in HTML format and display it on the web page using the ajax script.
Consider the process of creating a WebApi application from scratch. Create an ASP.Net application. WebApi. Select the Empty template and mark the options: MVC and WebApi.
The project references add FastReport.dll library.
Let's move on to creating a data model. Now the Model folder is empty. Right click on it and select Add, Class.
Call it Reports.cs. Add two fields: Id and ReportName:
You need to put report templates and a database file into the App_Data folder. In our case, these are two reports: "Simple List.frx" and "Barcode.frx";
Now, in the Controllers folder, add the controller ReportsController. It will have all the logic of the application. We do this using the context menu for the Controllers folder. Select Add -> Controller:
In the ReportsController class, we created an array of reports and two methods. We defined the names and identifiers of the reports 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 the identifier. From the query attribute, we can get the parameters format, inline, and parameter. They determine: the export format of the report, whether the report will be opened directly in the browser, the value of the parameter that is passed to the report. Particularly interesting is the method webReport.GetHtml (), which allows you to get the HTML view of the report. This is what we use to display on the page using ajax.
In the Web.config file, you need to add two handlers:
Now add the web page. Do the right click on the project and select Add-> HTML Page.
Traditionally we call the start page Index. We add the following code to the page:
As you can see from the code, we just load the HTML report file by requesting it from the service link.
Open the file WebApiConfig.cs from the folder App_Start. Add one more MapHttpRoute for the Index page:
In the same folder, the RouteConfig.cs file is located. It can be deleted.
Open the file Global.asax. Delete the line:
Now routing will be carried out only through WebApiConfig.
Launch the application and click the "Download" button:
We receive our report.
From the example considered, it is clear that working with web service for reports using Ajax is very simple.