如何在asp.net mvc 3 razor视图中使用reportviewer控件?

时间:2011-05-26 20:15:51

标签: asp.net-mvc-3 razor reportviewer

我正在尝试在剃须刀视图中使用mvc 3框架中的reportviewer控件。 online documentation谈论拖放。关于如何将其插入视图的任何建议。

8 个答案:

答案 0 :(得分:78)

以下解决方案仅适用于单页报告。有关详细信息,请参阅注释。

ReportViewer是一个服务器控件,因此无法在剃刀视图中使用。但是,您可以将ASPX视图页面,查看用户控件或包含ReportViewer的传统Web表单添加到应用程序中。

您需要确保已添加relevant handler into your web.config

如果您使用ASPX视图页面或查看用户控件,则需要进行设置 AsyncRendering为false以使报告正确显示。

更新

添加了更多示例代码。请注意,Global.asax中无需进行任何有意义的更改。

<强>的Web.Config

我的结局如下:

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=152368
  -->

<configuration>
  <appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
        <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>

    <authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn" timeout="2880" />
    </authentication>

    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
      </namespaces>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true"/>
    <handlers>
      <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    </handlers>
  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

<强>控制器

控制器动作非常简单。

作为奖励,File()动作将“TestReport.rdlc”的输出作为PDF文件返回。

using System.Web.Mvc;
using Microsoft.Reporting.WebForms;

...

public class PDFController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public FileResult File()
    {
        ReportViewer rv = new Microsoft.Reporting.WebForms.ReportViewer();
        rv.ProcessingMode = ProcessingMode.Local;
        rv.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
        rv.LocalReport.Refresh();

        byte[] streamBytes = null;
        string mimeType = "";
        string encoding = "";
        string filenameExtension = "";
        string[] streamids = null;
        Warning[] warnings = null;

        streamBytes = rv.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);

        return File(streamBytes, mimeType, "TestReport.pdf");
    }

    public ActionResult ASPXView()
    {
        return View();
    }

    public ActionResult ASPXUserControl()
    {
        return View();
    }
}

<强> ASPXView.apsx

ASPXView如下。

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>

<!DOCTYPE html>

<html>
<head runat="server">
    <title>ASPXView</title>
</head>
<body>
    <div>
        <script runat="server">
            private void Page_Load(object sender, System.EventArgs e)
            {
                ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
                ReportViewer1.LocalReport.Refresh();
            }
        </script>
        <form id="Form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">          
        </asp:ScriptManager>
        <rsweb:reportviewer id="ReportViewer1" runat="server" height="500" width="500" AsyncRendering="false"></rsweb:reportviewer>
        </form>        
    </div>
</body>
</html>

<强> ViewUserControl1.ascx

ASPX用户控件如下所示:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Register Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<script runat="server">
  private void Page_Load(object sender, System.EventArgs e)
  {
      ReportViewer1.LocalReport.ReportPath = Server.MapPath("~/Reports/TestReport.rdlc");
      ReportViewer1.LocalReport.Refresh();
  }
</script>
<form id="Form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" AsyncRendering="false"></rsweb:ReportViewer>
</form>

<强> ASPXUserControl.cshtml

剃刀观点。需要ViewUserControl1.ascx。

@{
    ViewBag.Title = "ASPXUserControl";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>ASPXUserControl</h2>
@Html.Partial("ViewUserControl1")

<强>参考

http://blogs.msdn.com/b/sajoshi/archive/2010/06/16/asp-net-mvc-handling-ssrs-reports-with-reportviewer-part-i.aspx

bind report to reportviewer in web mvc2

答案 1 :(得分:12)

这是一项简单的任务。您可以按照以下步骤操作。

  1. 在解决方案中创建一个文件夹,并将其命名为 报告
  2. 添加一个ASP.Net网络表单并将其命名为 ReportView.aspx
  3. 创建课程 ReportData ,并将其添加到 报告 文件夹中。将以下代码添加到类中。

    public class ReportData  
    {  
        public ReportData()  
        {  
            this.ReportParameters = new List<Parameter>();  
            this.DataParameters = new List<Parameter>();  
        }
    
        public bool IsLocal { get; set; }
        public string ReportName { get; set; }
        public List<Parameter> ReportParameters { get; set; }
        public List<Parameter> DataParameters { get; set; }
    }
    
    public class Parameter  
    {  
        public string ParameterName { get; set; }  
        public string Value { get; set; }  
    }
    
  4. 添加另一个类并将其命名为 ReportBasePage.cs 。在此类中添加以下代码。

    public class ReportBasePage : System.Web.UI.Page
    {
        protected ReportData ReportDataObj { get; set; }
    
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            if (HttpContext.Current != null)
                if (HttpContext.Current.Session["ReportData"] != null)
                {
                    ReportDataObj = HttpContext.Current.Session["ReportData"] as ReportData;
                    return;
                }
            ReportDataObj = new ReportData();
            CaptureRouteData(Page.Request);
        }
    
    
        private void CaptureRouteData(HttpRequest request)
        {
            var mode = (request.QueryString["rptmode"] + "").Trim();
            ReportDataObj.IsLocal = mode == "local" ? true : false;
            ReportDataObj.ReportName = request.QueryString["reportname"] + "";
            string dquerystr = request.QueryString["parameters"] + "";
            if (!String.IsNullOrEmpty(dquerystr.Trim()))
            {
                var param1 = dquerystr.Split(',');
                foreach (string pm in param1)
                {
                    var rp = new Parameter();
                    var kd = pm.Split('=');
                    if (kd[0].Substring(0, 2) == "rp")
                    {
                        rp.ParameterName = kd[0].Replace("rp", "");
                        if (kd.Length > 1) rp.Value = kd[1];
                        ReportDataObj.ReportParameters.Add(rp);
                    }
                    else if (kd[0].Substring(0, 2) == "dp")
                    {
                        rp.ParameterName = kd[0].Replace("dp", "");
                        if (kd.Length > 1) rp.Value = kd[1];
                        ReportDataObj.DataParameters.Add(rp);
                    }
                }
            }
        }
    }
    
  5. ScriptManager 添加到 ReportView.aspx 页面。现在向页面添加报表查看器。在报告查看器中,设置属性 AsyncRendering =“false” 。代码如下。

            

        <rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false"
            Width="1271px" Height="1000px" >
        </rsweb:ReportViewer>
    
  6. ReportView.aspx.cs

    中添加两个 NameSpace
    using Microsoft.Reporting.WebForms;
    using System.IO;
    
  7. System.Web.UI.Page 更改为 ReportBasePage 。只需使用以下代码替换您的代码。

    public partial class ReportView : ReportBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                RenderReportModels(this.ReportDataObj);
            }
        }
    
        private void RenderReportModels(ReportData reportData)
        {
            // This is the Data Access Layer from which a method is called to fill data to the list.
            RASolarERPData dal = new RASolarERPData();
            List<ClosingInventoryValuation> objClosingInventory = new List<ClosingInventoryValuation>();
    
            // Reset report properties.
            ReportViewerRSFReports.Height = Unit.Parse("100%");
            ReportViewerRSFReports.Width = Unit.Parse("100%");
            ReportViewerRSFReports.CssClass = "table";
    
            // Clear out any previous datasources.
            this.ReportViewerRSFReports.LocalReport.DataSources.Clear();
    
            // Set report mode for local processing.
            ReportViewerRSFReports.ProcessingMode = ProcessingMode.Local;
    
            // Validate report source.
            var rptPath = Server.MapPath(@"./Report/" + reportData.ReportName +".rdlc");
    
            //@"E:\RSFERP_SourceCode\RASolarERP\RASolarERP\Reports\Report\" + reportData.ReportName + ".rdlc";
            //Server.MapPath(@"./Report/ClosingInventory.rdlc");
    
            if (!File.Exists(rptPath))
                return;
    
            // Set report path.
            this.ReportViewerRSFReports.LocalReport.ReportPath = rptPath;
    
            // Set report parameters.
            var rpPms = ReportViewerRSFReports.LocalReport.GetParameters();
            foreach (var rpm in rpPms)
            {
                var p = reportData.ReportParameters.SingleOrDefault(o => o.ParameterName.ToLower() == rpm.Name.ToLower());
                if (p != null)
                {
                    ReportParameter rp = new ReportParameter(rpm.Name, p.Value);
                    ReportViewerRSFReports.LocalReport.SetParameters(rp);
                }
            }
    
            //Set data paramater for report SP execution
            objClosingInventory = dal.ClosingInventoryReport(this.ReportDataObj.DataParameters[0].Value);
    
            // Load the dataSource.
            var dsmems = ReportViewerRSFReports.LocalReport.GetDataSourceNames();
            ReportViewerRSFReports.LocalReport.DataSources.Add(new ReportDataSource(dsmems[0], objClosingInventory));
    
            // Refresh the ReportViewer.
            ReportViewerRSFReports.LocalReport.Refresh();
        }
    }
    
  8. 将文件夹添加到 报告 文件夹并将其命名为 报告 。现在,将 RDLC 报告添加到 报告/报告 文件夹,并将其命名为 ClosingInventory。 RDLC 即可。

  9. 现在添加一个Controller并将其命名为 ReportController 。在控制器中添加以下操作方法。

    public ActionResult ReportViewer()
        {                
            ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/";
    
            return View();
        }
    
  10. 添加视图页面,然后单击 ReportViewer 控制器。将视图页面命名为 ReportViewer.cshtml 。将以下代码添加到视图页面。

    @using (Html.BeginForm("Login"))
     { 
           @Html.DropDownList("ddlYearMonthFormat", new SelectList(ViewBag.YearMonthFormat, "YearMonthValue",
     "YearMonthName"), new { @class = "DropDown" })
    
    Stock In Transit: @Html.TextBox("txtStockInTransit", "", new { @class = "LogInTextBox" })
    
    <input type="submit" onclick="return ReportValidationCheck();" name="ShowReport"
                     value="Show Report" />
    
    }
    
  11. 添加 iframe 。设置Iframe的属性如下

    frameborder="0"  width="1000"; height="1000"; style="overflow:hidden;"
    scrolling="no"
    
  12. 将以下JavaScript添加到查看器中。

    function ReportValidationCheck() {
    
        var url = $('#hdUrl').val();
        var yearmonth = $('#ddlYearMonthFormat').val();      
        var stockInTransit = $('#txtStockInTransit').val()
    
        if (stockInTransit == "") {
            stockInTransit = 0;
        }
    
        if (yearmonth == "0") {
            alert("Please Select Month Correctly.");
        }
        else {
    
            //url = url + "dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
    
            url = "../Reports/ReportView.aspx?rptmode=local&reportname=ClosingInventory&parameters=dpSpYearMonth=" + yearmonth + ",rpYearMonth=" + yearmonth + ",rpStockInTransit=" + stockInTransit;
    
            var myframe = document.getElementById("ifrmReportViewer");
            if (myframe !== null) {
                if (myframe.src) {
                    myframe.src = url;
                }
                else if (myframe.contentWindow !== null && myframe.contentWindow.location !== null) {
                    myframe.contentWindow.location = url;
                }
                else { myframe.setAttribute('src', url); }
            }
        }
    
        return false;
    }
    
  13. Web.config 文件将以下密钥添加到 appSettings 部分

    add key="UnobtrusiveJavaScriptEnabled" value="true"
    
  14. system.web 处理程序 部分添加以下密钥

    add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
    
  15. 将您的数据源更改为您自己的数据源。这个解决方案非常简单,我想每个人都会喜欢它。

答案 2 :(得分:7)

我正在使用带有SSRS 2008的ASP.NET MVC3,在尝试从远程服务器获取报告时,我无法让@Adrian为我100%工作。

最后,我发现我需要将 ViewUserControl1.ascx 中的Page_Load方法更改为:

ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://<Server Name>/reportserver");
serverReport.ReportPath = "/My Folder/MyReport";
serverReport.Refresh();

我错过了 ProcessingMode.Remote

参考文献:

http://msdn.microsoft.com/en-us/library/aa337091.aspx - ReportViewer

答案 3 :(得分:7)

以下是在MVC .aspx视图中直接集成报表查看器控件(以及任何asp.net服务器端控件)的完整解决方案,该视图也适用于具有多个页面的报表(与Adrian Toman的回答不同) )并将AsyncRendering设置为true,(基于Steve Sanderson的“Pro ASP.NET MVC Framework”)。

基本上需要做的是:

  1. 使用runat =“server”

  2. 添加表单
  3. 添加控件,(对于报表查看器控件,它有时甚至可以使用AsyncRendering =“True”,但并非总是如此,因此请检查您的具体情况)

  4. 使用runat =“server”的脚本标记添加服务器端脚本

  5. 使用下面显示的代码覆盖Page_Init事件,以启用PostBack和Viewstate

  6. 这是一个演示:

    <form ID="form1" runat="server">
        <rsweb:ReportViewer ID="ReportViewer1" runat="server" />
    </form>
    <script runat="server">
        protected void Page_Init(object sender, EventArgs e)
        {
            Context.Handler = Page;
        }
        //Other code needed for the report viewer here        
    </script>
    

    当然建议充分利用MVC方法,在控制器中准备所有需要的数据,然后通过ViewModel将其传递给视图。

    这将允许重用View!

    然而,这仅针对数据说,每次回发都需要这样,或者即使它们仅在初始化时需要初始化,如果它不是数据密集的,并且数据也不依赖于PostBack和ViewState值。

    但是,即使数据密集,有时也可以封装到lambda表达式中,然后传递给要在那里调用的视图。

    但有几点注意事项:

    • 通过这样做,视图本质上变成了一个具有所有缺点的Web表单(即回发,以及非Asp.NET控件被覆盖的可能性)
    • 覆盖Page_Init的黑客没有记录,并且可能随时更改

答案 4 :(得分:6)

NuGet中有一个MvcReportViewer助手。

http://www.nuget.org/packages/MvcReportViewer/

这是详细信息:

https://github.com/ilich/MvcReportViewer

我使用过这个。它很棒。

答案 5 :(得分:1)

文档是指ASP.NET应用程序 您可以尝试查看我的回答here 我的回复附有一个例子 可以找到ASP.NET MVC3的另一个示例here

答案 6 :(得分:1)

您不仅需要使用asp.net页面,还需要

如果使用Entity Framework或LinqToSql(如果使用部分类)将数据移动到单独的项目中,则报表设计者无法看到类。

将报告移动到另一个项目/ dll,VS10有错误,asp.net项目无法在Web应用程序中看到对象数据源。然后将报告从dll流式传输到您的mvc项目aspx页面。

这适用于mvc和webform项目。在本地模式下使用sql报告并不是一种很好的开发体验。如果导出大型报告,还要观察您的Web服务器内存。报告查看器/导出设计非常糟糕。

答案 7 :(得分:1)

可以在不使用iFrame或aspx页面的情况下将SSRS报告显示在MVC页面上。

这里解释了大部分工作:

http://geekswithblogs.net/stun/archive/2010/02/26/executing-reporting-services-web-service-from-asp-net-mvc-using-wcf-add-service-reference.aspx

该链接说明了如何创建Web服务和MVC操作方法,该方法允许您调用报告服务并将Web服务的结果呈现为Excel文件。通过对示例中的代码进行少量更改,您可以将其呈现为HTML。

然后你需要做的就是使用一个按钮调用一个javascript函数,该函数对你的MVC动作进行AJAX调用,返回报告的HTML。当AJAX调用返回HTML时,只需用这个HTML替换div。

我们使用AngularJS所以下面的例子是那种格式,但它可以是任何javascript函数

$scope.getReport = function()
{
    $http({
        method: "POST",
        url: "Report/ExportReport",
        data: 
                [
                    { Name: 'DateFrom', Value: $scope.dateFrom },
                    { Name: 'DateTo', Value: $scope.dateTo },
                    { Name: 'LocationsCSV', Value: $scope.locationCSV }
                ]

    })
    .success(function (serverData)
    {
        $("#ReportDiv").html(serverData);
    });

};

动作方法 - 主要取自上述链接......

    [System.Web.Mvc.HttpPost]
    public FileContentResult ExportReport([FromBody]List<ReportParameterModel> parameters)
    {
         byte[] output;
         string extension, mimeType, encoding;
         string reportName = "/Reports/DummyReport";
         ReportService.Warning[] warnings;
         string[] ids;

     ReportExporter.Export(
            "ReportExecutionServiceSoap" 
            new NetworkCredential("username", "password", "domain"),
            reportName,
            parameters.ToArray(),
            ExportFormat.HTML4,
            out output,
            out extension,
            out mimeType,
            out encoding,
            out warnings,
            out ids
        );

        //-------------------------------------------------------------
        // Set HTTP Response Header to show download dialog popup
        //-------------------------------------------------------------
        Response.AddHeader("content-disposition", string.Format("attachment;filename=GeneratedExcelFile{0:yyyyMMdd}.{1}", DateTime.Today, extension));
        return new FileContentResult(output, mimeType);
    }

因此,结果是您可以将参数传递给SSRS报告服务器,该服务器返回您呈现为HTML的报告。一切都出现在一页上。这是我能找到的最佳解决方案