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