當你使用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>
運行應用程序並獲取報表。