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

Aru*_*run 60 reportviewer razor asp.net-mvc-3

我正在尝试在剃须刀视图中使用reportviewer控件,在mvc 3框架中.该在线文档拖放会谈.有关如何将其插入视图的任何建议.

Adr*_*man 78

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

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

您需要确保已将相关处理程序添加到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>
Run Code Online (Sandbox Code Playgroud)

调节器

控制器动作非常简单.

作为奖励,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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

ASPXUserControl.cshtml

剃刀视图.需要ViewUserControl1.ascx.

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

参考

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

将报告绑定到web mvc2中的reportviewer

  • 你是用ServerReports测试过的吗?因为它为我呈现了初始报告页面,但是当我点击控件中的任何按钮(例如"下一页")时,它什么也没做. (7认同)
  • @AdrianToman请更新答案,表明它只适用于第一页,以便未来的读者不应该把时间花在那上面 (3认同)
  • 我对ServerReports有同样的问题,第一页渲染正常,但任何回调都不会产生任何问题. (2认同)

Md.*_*lam 12

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

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

    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; }  
    }
    
    Run Code Online (Sandbox Code Playgroud)
  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);
                    }
                }
            }
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  5. ScriptManager添加到ReportView.aspx页面.现在添加一个报表查看器到页面.在报表查看器中,设置属性AsyncRendering ="false".代码如下.

        <rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false"
            Width="1271px" Height="1000px" >
        </rsweb:ReportViewer>
    
    Run Code Online (Sandbox Code Playgroud)
  6. ReportView.aspx.cs中添加两个NameSpace

    using Microsoft.Reporting.WebForms;
    using System.IO;
    
    Run Code Online (Sandbox Code Playgroud)
  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();
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  8. 将文件夹添加到Reports文件夹并将其命名为Report.现在将RDLC报告添加到Reports/Report文件夹并将其命名为ClosingInventory.rdlc.

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

    public ActionResult ReportViewer()
        {                
            ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/";
    
            return View();
        }
    
    Run Code Online (Sandbox Code Playgroud)
  10. 添加视图页面单击ReportViewer Controller.将视图命名为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" />
    
    }
    
    Run Code Online (Sandbox Code Playgroud)
  11. 添加iframe.如下设置Iframe的属性

    frameborder="0"  width="1000"; height="1000"; style="overflow:hidden;"
    scrolling="no"
    
    Run Code Online (Sandbox Code Playgroud)
  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;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  13. Web.config文件将以下键添加到 appSettings部分

    add key="UnobtrusiveJavaScriptEnabled" value="true"
    
    Run Code Online (Sandbox Code Playgroud)
  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"
    
    Run Code Online (Sandbox Code Playgroud)
  15. 将您的数据源更改为您自己的.这个解决方案非常简单,我想每个人都会喜欢它.

  • 哈哈为简单的任务和400线答案 (50认同)
  • 从没有人知道的库中声明了两个神秘的变量,`RASolarERPData dal`和`List <ClosingInventoryValuation> objClosingInventory`. (5认同)

wil*_*sjd 7

我正在使用ASP.NET MVC3和SSRS 2008,当我试图从远程服务器获取报告时,我无法让@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();
Run Code Online (Sandbox Code Playgroud)

我一直在错过ProcessingMode.Remote.

参考文献:

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


yoe*_*alb 7

这里是直接集成的报表查看器控制在MVC的.aspx视图的完整解决方案(以及任何asp.net服务器端控件),这也将在多页(不像阿德里安·托曼的答案)报告工作,并与AsyncRendering设置为true,(基于Steve Sanderson的"Pro ASP.NET MVC Framework").

人们需要做的基本上是:

  1. 使用runat ="server"添加表单

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

  3. 使用runat ="server"的脚本标记添加服务器端脚本

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

这是一个演示:

<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>
Run Code Online (Sandbox Code Playgroud)

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

这将允许重用View!

然而这仅仅是说这个是需要每一个数据回发,或者即使他们只需要初始化,如果它不是数据密集型和数据也没有依赖于回发和ViewState的值.

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

但有两点注意事项:

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


Hay*_*iza 6

NuGet中有一个MvcReportViewer帮助器.

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

这是详细信息:

https://github.com/ilich/MvcReportViewer

我用过这个.它很棒.