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

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

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

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

· FastReport.dll;网络

· FastReport.Web.dll。spa

你能够在FastReport.Net应用程序的文件夹中找到它们。code

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

声明库:htm

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类的实例。blog

接下来,建立一个变量来存储包含报表的文件夹的路径。对于该报表所需的数据,咱们建立一个数据集并加载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>

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

相关文章
相关标签/搜索