Fastreport.net 如何在开发MVC应用程序时使用报表

当你使用MVC模板创建自己的Web项目,会出现一个合理的问题 - 如何在其中使用FastReport.Net Web报表?

在这篇文章中,我会为你演示如何做到这一点。

由于在MVC体系结构中,视图与逻辑分离,所以你将无法使用WebReport的可视化组件。我将不得不使用控制器代码中的报表,然后将其转移到视图。例如,在这里我使用了一个标准的MVC Web应用程序。首先,我们将必要的库连接到项目中:

· FastReport.dll;

· FastReport.Web.dll。

你可以在FastReport.Net应用程序的文件夹中找到它们。

我决定在站点的主页上发布一个报表。因此,我们将使用 HomeController.cs 中的报表。

声明库:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FastReport.Web;
using System.Web.UI.WebControls;

要使用 Index () 方法,请添加以下代码:

public ActionResult Index()
 {
 WebReport webReport = new WebReport();
 
 string report_path = "C:\\Program Files (x86)\\FastReports\\FastReport.Net\\Demos\\Reports\\";
 System.Data.DataSet dataSet = new System.Data.DataSet();
 dataSet.ReadXml(report_path + "nwind.xml");
 webReport.Report.RegisterData(dataSet, "NorthWind");
 webReport.Report.Load(report_path + "Simple List.frx");
 ViewBag.WebReport = webReport;
 return View();
 }

我们考量一下细节。在第一行中,我们创建了一个WebReport类的实例。

接下来,创建一个变量来存储包含报表的文件夹的路径。对于该报表所需的数据,我们创建一个数据集并加载xml数据库。

现在您需要使用 RegisterData () 方法在报表对象中注册数据源。我们使用 Load () 方法来加载报表模板。

ViewBag是对象ViewData的一个封装,用于将数据从控制器传输到视图。在这种情况下,我们会将报表传送到视图索引,本质上来讲就是主页。

我们转到演示:

网页代码是:

@{
 ViewBag.Title = "Home Page";
}
@ViewBag.WebReport.GetHtml()

我删除了不必要的,留下了一个页面标题,而我们的报表,以HTML格式呈现。

也就是说,要在页面上显示报表,只需添加代码:

@ ViewBag.WebReport.GetHtml()

相应的控制器会发送一个报表给它。

我们需要在视图初始化中添加脚本:

<head>
…
@WebReportGlobals.Scripts()
@WebReportGlobals.Styles() 
…
</head> 

在我们的例子中,文件 _Layout.cshtml:

它仍然只是纠正位于Views文件夹中的Web.config。

我们为网络报表添加命名空间:

<namespaces><add namespace="FastReport" />
 <add namespace="FastReport.Web" />
 </namespaces>

在项目的根目录,还有另一个Web.config。我们往里面添加一个处理句柄:

<handlers><add name="FastReportHandler" path="FastReport.Export.axd" verb="*" type="FastReport.Web.Handlers.WebExport"/>
 </handlers>

运行应用程序并获取报表。

 

posted @ 2018-07-02 10:42  ymnets  阅读(2202)  评论(4编辑  收藏  举报