在 ASP.net MVC 站点中查看 SSRS 报告

发布于 2024-10-02 01:12:27 字数 91 浏览 0 评论 0 原文

有没有办法将 SQL Server Reporting Services 报表查看器控件放在 ASP.net MVC 视图上?如果不是……实现这一目标的最佳方法是什么?

Is there a way to put a SQL Server Reporting Services report viewer control on an ASP.net MVC view? If not...what is the best way to accomplish this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

墨落成白 2024-10-09 01:12:27

不,不在 MVC 视图中。但是您可以将包含服务器控件的 Web 表单页面与您的 MVC 站点混合在一起。

嗯,刚刚在 google 上搜索“混合 asp.net mvc 和 web 表单”来找到一些示例,然后 google 质疑我是否是人类:)

无论如何,这里有一个链接 - http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp。 net-mvc - 有一些。出于同样的原因(报告控件),我也在 MVC 站点中执行了此操作。

No, not in a MVC view. But you can have a web forms pages which have server controls in them mixed in with your MVC site.

Hmm, just googled "mix asp.net mvc and web forms" to find some examples, and google questioned whether I'm human or not :)

Anyway, here's a link - http://www.packtpub.com/article/mixing-asp.net-webforms-and-asp.net-mvc - there's a few out there. I've also done this in a MVC site for the same reason - the report control.

初心未许 2024-10-09 01:12:27

不,如果将 ReportViewer 控件放置在 MVC 视图中,它将无法工作,因为它需要 ViewState。您必须创建一个老式的 Web 表单并将 ReportViewer 放在那里。

我在一个项目中使用的解决方案是创建一个自定义路由处理程序,这样我仍然可以使用 URL 路由。路由处理程序将从 RouteData 集合中获取报告名称等参数,创建 Web 表单的实例,并通过公共属性将参数传递给它。 Web 表单将在 Page_Load 中读取这些内容并配置 ReportViewer 控件。

// Configure a route in Global.asax.cs that is handled by a ReportRouteHandler
routes.Add("ReportRoute", new Route("Reports/{reportName}",
                                    new ReportRouteHandler());

public class ReportRouteHandler : IRouteHandler {
    public IHttpHandler GetHttpHandler(RequestContext requestContext) {
        var reportName = requestContext.RouteData.Values["reportName"] as string;

        var webform = BuildManager
            .CreateInstanceFromVirtualPath("~/Path/To/ReportViewerWebForm.aspx",
                                           typeof(Page)) as ReportViewerWebForm;
        webform.ReportToShow = reportName;
        return webform;
    }
}

当然,如果您决定使用这种方法,此代码只是一个起点。我创建的那个在返回之前还进行了一些用户身份验证和参数验证。

更新:看起来如果您使用的是 ASP.NET 4.0,大部分工作都可以自动完成

No, the ReportViewer control won't work if you place it in an MVC view, since it requires ViewState. You'll have to create an old-school web form and put the ReportViewer there instead.

A solution I used in a project I worked on was to create a custom route handler, so I could still make use of URL routing. The route handler would take parameters like the report name from the RouteData collection, create an instance of my web form, and pass the parameters to it via public properties. The web form would read these in Page_Load and configure the ReportViewer control.

// Configure a route in Global.asax.cs that is handled by a ReportRouteHandler
routes.Add("ReportRoute", new Route("Reports/{reportName}",
                                    new ReportRouteHandler());

public class ReportRouteHandler : IRouteHandler {
    public IHttpHandler GetHttpHandler(RequestContext requestContext) {
        var reportName = requestContext.RouteData.Values["reportName"] as string;

        var webform = BuildManager
            .CreateInstanceFromVirtualPath("~/Path/To/ReportViewerWebForm.aspx",
                                           typeof(Page)) as ReportViewerWebForm;
        webform.ReportToShow = reportName;
        return webform;
    }
}

This code is just a starting point if you decide to use this approach, of course. The one I created also did some user authentication and parameter validation before returning.

Update: Looks like if you're using ASP.NET 4.0, most of this can be done automatically!

浅暮の光 2024-10-09 01:12:27

在 MVC 中实现 SSRS ReportViewer 控件包含两个问题:

  1. 您至少需要添加正确的依赖项、处理程序和ReportViewer 控件的配置(无论项目类型如何)。
  2. 更棘手的障碍在于混合 WebForms 和 MVC。我们需要一种呈现和路由传入请求的方法,以便它们可以由 WebForms 页面、控件和操作进行处理。

问题 1 - 配置 ReportViewer

如果您过去已经在设置 ​​ReportViewer 控件方面做了很多工作,那么这可能是旧帽子,您可以跳到第 2 部分。

  1. 添加包/reference - ReportViewer 控件位于 Microsoft.ReportViewer.WebForms.dll 中。您可以通过添加 Microsoft.ReportViewer.WebForms来自nuget的包:

    “Nuget

  2. Web.config 处理程序 - 根据 ReportViewer 的 Web.config 设置,以及 这个问题您需要将以下内容添加到您的web.config中:

    ;
      
        <添加动词=“*”路径=“Reserved.ReportViewerWebControl.axd” 
             类型=“Microsoft.Reporting.WebForms.HttpHandler”,
                   Microsoft.ReportViewer.WebForms,版本=10.0.0.0,文化=中性,
                   PublicKeyToken=b03f5f7f11d50a3a" />
      
    
    <系统.web服务器>
      <处理程序>
        <删除名称=“ReportViewerWebControlHandler”/>
        <添加名称=“ReportViewerWebControlHandler”preCondition=“integratedMode”
             动词=“*”路径=“Reserved.ReportViewerWebControl.axd” 
             类型=“Microsoft.Reporting.WebForms.HttpHandler”, 
                   Microsoft.ReportViewer.WebForms,版本=10.0.0.0,文化=中性,
                   PublicKeyToken=b03f5f7f11d50a3a"/>>
      
    
    

    根据这个关于重复键的问题,通常最容易删除然后重新添加网络服务器配置< /sup>

  3. 修复损坏的图像请求 - ReportViewer 中存在一个已知缺陷 blank.gif 图像未加载,因此您可以将以下修复添加到 global.asax.cs

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpRequest req = HttpContext.Current.Request;
        if (req.Url.PathAndQuery.StartsWith("/Reserved.ReportViewerWebControl.axd") &&
            !req.Url.ToString().ToLower().Contains("迭代") &&
            !String.IsNullOrEmpty(req.QueryString["ResourceStreamID"]) &&
            req.QueryString["ResourceStreamID"].ToLower().Equals("blank.gif"))
        {
            Context.RewritePath(String.Concat(req.Url.PathAndQuery, "&IterationId=0"));
        }
    }
    
  4. IgnoreRoute .axd -如果尚不存在,请确保在您的 RouteConfig.cs允许 ScriptResources

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
  5. Add ReportViewerPage.aspx - 添加一个将保存 ReportViewer 控件实例的 WebForm 页面。为了工作,该控件需要找到 ScriptManager 控件并将其放置在

    内。
    因此,您的新 .aspx 页面应如下所示:

    <%@ 页面语言="C#" AutoEventWireup="true" CodeBehind="ReportViewerPage.aspx.cs" Inherits="MVCAppWithReportViewer.ReportViewerPage" %>
    <%@ Register TagPrefix="rsweb" Namespace="Microsoft.Reporting.WebForms" Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
    
    
    
    
        <标题>报告查看器
    
    <正文>
        <表单 id="form1" runat="服务器">
            
            
        
    
    
    
  6. Page_Load 上连接 ReportViewer - 假设您已经将 SSRS 报告完全部署到报告服务器上可以在如下地址找到:

    http://ReportServerName/Reports/Pages/Report.aspx?ItemPath=%2fCompany%2fClientReport

    然后您的新 WebForm 页面中的代码隐藏应如下所示:

    公共部分类 ReportViewerPage : System.Web.UI.Page
    {
        protected void Page_Load(对象发送者,EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // 确认报告属性(也可在属性中设置)
                ReportViewer.ProcessingMode=ProcessingMode.Remote;
    
                // 配置变量
                var reportServer = "报表服务器名称";
                var reportPath = "/公司/";
                var 报告名称 = "ClientReport";    
    
                // 报告设置
                var serverReport = new ServerReport();
                serverReport = ReportViewer.ServerReport;
                serverReport.ReportServerUrl = new Uri($@"http://{reportServer}/ReportServer");
                serverReport.ReportPath = $@"{reportPath}{reportName}";
    
                // 报告输入
                var 参数 = new List();
                参数.Add(new ReportParameter("User_uid", "1"));
                serverReport.SetParameters(参数);
    
                // 运行报告
                serverReport.Refresh();
            }
        }
    }
    

  7. 查看报告 - 此时,您应该能够通过选择在浏览器中查看来单独查看报告Ctrl + Shift + W

    “在浏览器中查看”"

问题 2 - 混合 WebForms 和 MVC

首先,让我们快速剖析两者之间的路由差异如何加载这些控件以及随后更新

  • MVC 路由将类似于 {controller}/{action}/{id} ,路由引擎将在其中自动查找具有指定名称的 ControllerAction 以及传入请求将由该方法处理。在任何页面请求中,无论是页面加载、表单提交、按钮点击、锚点导航还是 ajax 调用,所执行的确切方法始终在 url {action} 中指定。

  • WebForms 通过查找物理 .aspx 页面地址来路由到代码,然后使用 ViewState & PostData 连接并触发该页面/控件上的事件。

    这是WebForms 中不同路由格式的图示。这是一个简单的按钮单击事件,它将向父页面提交一个帖子,并根据提交的事件数据在页面内引发适当的事件:

    “ASP.NET

这对我们来说是一个相当大的限制可用的解决方案。 ReportViewer 控件没有什么特别之处。它只是一组复杂的 UserControl 类,通过回发当前地址以及 ViewState 和事件信息来响应单击和其他输入事件。因此,ReportViewer 的路由和导航中包含的任何假设都需要保留到我们的 MVC 包装器中。

  1. 选项 1 - 为 .aspx 页面添加路由

    从 MVC 4.0+ 开始,您可以使用 使用 WebForms 进行 URL 路由。通过添加 地图页面路线 (请注意页面 部分) 将路由映射到物理文件。因此,将以下内容添加到您的 RouteConfig.cs 中:

    routes.MapPageRoute(
        路线名称:“ReportViewer”,
        RouteUrl: "ReportViewer/{reportName}",
        物理文件:“~/ReportViewerPage.aspx”
    );
    

    当您导航到地址 ~/Reports/reportName 时,报告将运行。这可能会从控制器操作内部调用,可能会使用一些用户输入的参数或 web.config 连接字符串。有很多管理 ASP.NET 状态的方法和< a href="https://msdn.microsoft.com/en-us/library/6c3yckfw.aspx" rel="nofollow noreferrer">将值传递到 ASP.NET Web 表单页面。一种选择是将信息存储在会话中,并在控制器中像这样重定向:

    HttpContext.Session[reportSetup.ReportName] = new ReportSetup() {ReportName = "ClientReport"}; //报告设置;}
    return RedirectToRoute("ReportViewer", new { reportName = reportSetup.ReportName});
    

    然后,在 .aspx 页面内,您可以从 RouteData 值中获取 reportName 以及会话中的任何设置参数:

    // 从路由中获取报告名称
    string reportName = Page.RouteData.Values["reportName"].ToString();
    
    // 从会话中获取模型并清除
    ReportSetup setup = (ReportSetup)HttpContext.Current.Session[报告名称];
    

    优点

    • 大多数路由似乎在默认情况下都能正常工作,并且 AJAX 控件也能正常工作,因此您可以设置 AyncRendering=True

    缺点

  2. 选项 2 - 将 .ascx 嵌套在页面上的 PartialView

    改编自如何将 ReportViewer 控件与 Razor 一起使用?,您可以使用 .ascx 控件,只要它们继承自 System.Web.Mvc.ViewUserControl

    创建一个名为 ReportViewerControl.ascx 的新 Web 窗体用户控件,如下所示:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ReportViewerControl.ascx.cs" Inherits="MVCAppWithReportViewer.ReportViewerControl" %>
    <%@ Register TagPrefix="rsweb" Namespace="Microsoft.Reporting.WebForms" Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
    
    <表单 id="form1" runat="服务器">
        AsyncRendering="False" />
        EnablePartialRendering="false" />
    
    

    <块引用>

    注意:您必须设置AsyncRendering="False"EnablePartialRendering="false"

    在后面的代码中,您需要将继承类型从 System.Web.UI.UserControl 替换为 System.Web.Mvc.ViewUserControl 。

    Page_Init 上,您需要设置 Context.HandlerPage 以便正确注册事件。

    因此,ReportViewerControl.ascx.cs 应该如下所示:

    公共部分类 ReportViewerControl : System.Web.Mvc.ViewUserControl
    {
        protected void Page_Init(对象发送者,EventArgs e)
        {
            // 正确处理报告事件所必需的。
            Context.Handler = 页面;
        }
    
        protected void Page_Load(对象发送者,EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                /* ... 报告设置 ... */ 
                serverReport.Refresh();
            }
        }
    }
    

    为了呈现报告,请将以下内容添加到控制器视图中:

    @Html.Partial("ReportViewerControl", Model)
    

    然后在 ReportViewerControl.ascx.cs Page_Load 事件中,您可以从 ViewUserControl.Model 属性如下:

    ReportSetup setup = (ReportSetup)Model;
    

    优点

    • 可以构建到主 _layout.cshtml 中并在常规视图中使用
    • 可以直接传递模型

    缺点

    • AsyncRendering 必须设置为 false,因此分页和排序等交互会导致整页刷新,有时会出现不稳定的情况。 Brian Hartman 有一个专门针对 ReportViewer 的博客,其中讨论了 异步渲染以及随之而来的所有包袱

进一步阅读

Implementing a SSRS ReportViewer control in MVC consists of two problems:

  1. Minimally, you'll need to add the right dependencies, handlers, and configuration for the ReportViewer control (regardless of project type).
  2. The trickier hurdle is in Mixing WebForms and MVC. We need a way of rendering and routing incoming requests so they will be handled by WebForms pages, controls, and actions.

Problem 1 - Configuring the ReportViewer

If you've done a lot with setting up ReportViewer controls in the past, this might be old hat and you can skip to section 2.

  1. Add package/reference - The ReportViewer control lives in the Microsoft.ReportViewer.WebForms.dll. You can include in your project by adding the Microsoft.ReportViewer.WebForms package from nuget:

    Nuget - Microsoft.ReportViewer.WebForms

  2. Web.config Handlers - Per this article on Web.config Settings for ReportViewer, and this SO question you'll need to add the following to your web.config:

    <system.web>
      <httpHandlers>
        <add verb="*" path="Reserved.ReportViewerWebControl.axd" 
             type="Microsoft.Reporting.WebForms.HttpHandler,
                   Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral,
                   PublicKeyToken=b03f5f7f11d50a3a" />
      </httpHandlers>
    </system.web>
    <system.webServer>
      <handlers>
        <remove name="ReportViewerWebControlHandler" />
        <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>
    

    Per this question on duplicate keys, it's typically easiest to remove and then re-add webserver configs

  3. Fix broken Image Requests - there's a known defect in ReportViewer with blank.gif images not loading so you can add the following fix to your global.asax.cs:

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpRequest req = HttpContext.Current.Request;
        if (req.Url.PathAndQuery.StartsWith("/Reserved.ReportViewerWebControl.axd") &&
            !req.Url.ToString().ToLower().Contains("iteration") &&
            !String.IsNullOrEmpty(req.QueryString["ResourceStreamID"]) &&
            req.QueryString["ResourceStreamID"].ToLower().Equals("blank.gif"))
        {
            Context.RewritePath(String.Concat(req.Url.PathAndQuery, "&IterationId=0"));
        }
    }
    
  4. IgnoreRoute .axd - If it's not already there, make sure to allow ScriptResources in your RouteConfig.cs:

    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
  5. Add ReportViewerPage.aspx - Add a WebForm page that will hold an instance of the ReportViewer control. In order to work, that control needs to find a ScriptManager control and be placed inside of a <form runat="server" >.
    So your new .aspx page should look something like this:

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ReportViewerPage.aspx.cs" Inherits="MVCAppWithReportViewer.ReportViewerPage" %>
    <%@ Register TagPrefix="rsweb" Namespace="Microsoft.Reporting.WebForms" Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <title>Report Viewer</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <rsweb:ReportViewer ID="ReportViewer" runat="server" 
                                Height="100%" Width="100%" 
                                SizeToReportContent="True" ProcessingMode="Remote" />
            <asp:ScriptManager ID="ScriptManager1" runat="server" />
        </form>
    </body>
    </html>
    
  6. Wire up ReportViewer on Page_Load - Assuming, you already have an SSRS report fully deployed to a reporting server which is available at an address like this:

    http://ReportServerName/Reports/Pages/Report.aspx?ItemPath=%2fCompany%2fClientReport

    Then your code-behind in your new WebForm page should look like this:

    public partial class ReportViewerPage : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                // confirm report properties (also setable in attributes)
                ReportViewer.ProcessingMode = ProcessingMode.Remote;
    
                // config variables
                var reportServer = "ReportServerName";
                var reportPath = "/Company/";
                var reportName = "ClientReport";    
    
                // report setup
                var serverReport = new ServerReport();
                serverReport = ReportViewer.ServerReport;
                serverReport.ReportServerUrl = new Uri($@"http://{reportServer}/ReportServer");
                serverReport.ReportPath = $@"{reportPath}{reportName}";
    
                // report input
                var parameters = new List<ReportParameter>();
                parameters.Add(new ReportParameter("User_uid", "1"));
                serverReport.SetParameters(parameters);
    
                // run report
                serverReport.Refresh();
            }
        }
    }
    
  7. View Report - At this point you should be able to view your report on it's own by selecting View in Browser or Ctrl + Shift + W

    View in Browser

Problem 2 - Mixing WebForms and MVC

First, let's quickly dissect the routing differences between how these controls are loaded and subsequently updated

  • MVC routes will look something like this {controller}/{action}/{id} where the routing engine will automatically find a Controller and Action with the specified name and incoming requests will be handled by that method. On any page request, whether from page load, form submit, button clicks, anchor navigation, or ajax calls, the exact method being executed is always specified in the url {action}.

  • WebForms routes to code by finding the physical .aspx page address, and then uses ViewState & PostData to wire up and fire events on that page / control.

    Here's an illustration of different routing formats in WebForms. And here's a simple button click event which will submit a post back to the parent page and raise the appropriate events within the page based on the event data submitted:

    ASP.NET WebForms - Postback

This is a pretty big constraint on our solutions available. Nothing is special about the ReportViewer control. It's just a sophisticated set of UserControl classes that respond to click and other input events by posting back the current address along with the ViewState and Event info. So whatever assumptions were baked into the routing and navigation of the ReportViewer will need to persist into our MVC wrapper.

  1. Option 1 - Add Route for .aspx page

    As of MVC 4.0+, you can use URL Routing with WebForms. This mixes well with MVC by adding a MapPageRoute (note the Page part) to map a route to a physical file. So add the following to your RouteConfig.cs:

    routes.MapPageRoute(
        routeName: "ReportViewer",
        routeUrl: "ReportViewer/{reportName}",
        physicalFile: "~/ReportViewerPage.aspx"
    );
    

    The report will run when you navigate to the address ~/Reports/reportName. This will probably be invoked from inside a controller action, perhaps with some user entered parameters or web.config connection strings. There are lots of ways to manage state in ASP.NET and Pass Values to ASP.NET Web Forms Pages. One option would be to stash the info in the Session and Redirect like this in your controller:

    HttpContext.Session[reportSetup.ReportName] = new ReportSetup() {ReportName = "ClientReport"}; //reportSetup;}
    return RedirectToRoute("ReportViewer", new { reportName = reportSetup.ReportName});
    

    Then, inside the .aspx page, and you can grab the reportName from the RouteData Values and any setup params from the session:

    // get report name from route
    string reportName = Page.RouteData.Values["reportName"].ToString();
    
    // get model from session and clear
    ReportSetup setup = (ReportSetup)HttpContext.Current.Session[reportName];
    

    Pros:

    • Most of the routing seems to work by default, and AJAX controls work fine, so you can set AyncRendering=True

    Cons:

    • It's hard to use an ASP Web Form with a Razor MVC Layout so rendering will take users out of the flow of the rest of the application.
    • Also, report values have to be exposed as part of the URL or passed indirectly via session (as opposed to hydrating directly onto the object).
  2. Option 2 - Nest .ascx inside PartialView on your Page

    Adapted from How can I use a ReportViewer control with Razor?, you can consume .ascx controls in PartialViews as long as they inherit from System.Web.Mvc.ViewUserControl.

    Create a new Web Forms User Control called ReportViewerControl.ascx that looks like this:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ReportViewerControl.ascx.cs" Inherits="MVCAppWithReportViewer.ReportViewerControl" %>
    <%@ Register TagPrefix="rsweb" Namespace="Microsoft.Reporting.WebForms" Assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
    
    <form id="form1" runat="server">
        <rsweb:ReportViewer ID="ReportViewer" runat="server" 
                            Height="100%" Width="100%"  
                            SizeToReportContent="True" ProcessingMode="Remote"
                            AsyncRendering="False" />
        <asp:ScriptManager ID="ScriptManager1" runat="server" 
                           EnablePartialRendering="false"  />
    </form>
    

    Note: You must set AsyncRendering="False" and EnablePartialRendering="false"

    In the code behind you'll need to replace the inheritance type from System.Web.UI.UserControl to System.Web.Mvc.ViewUserControl.

    And on Page_Init, you'll need to set the Context.Handler to Page so events are registered properly.

    So the ReportViewerControl.ascx.cs should look like this:

    public partial class ReportViewerControl : System.Web.Mvc.ViewUserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            // Required for report events to be handled properly.
            Context.Handler = Page;
        }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                /* ... report setup ... */ 
                serverReport.Refresh();
            }
        }
    }
    

    In order to render the report, add the following to your controller view:

    @Html.Partial("ReportViewerControl", Model)
    

    And then in the ReportViewerControl.ascx.cs Page_Load event, you can retrieve the passed in model from the ViewUserControl.Model property like this:

    ReportSetup setup = (ReportSetup)Model;
    

    Pros:

    • Can build into master _layout.cshtml and consume in regular views
    • Can pass model directly

    Cons:

Further Reading:

提赋 2024-10-09 01:12:27

现在有一个 MvcReportViewer 助手。我们可以从 NuGet 获取它。

GitHub 上的项目网站

NuGet 包一个>

Now there's a MvcReportViewer helper. We can get it from NuGet.

Project Site on GitHub

NuGet Package

秋意浓 2024-10-09 01:12:27

这有点简单,需要一些修复才能将一些像样的东西传递给 MVC 中的视图

public ActionResult Index()
{
    /*Credentials of a user that has access to SSRS*/
    string userid = "UserId";
    string password = "MyPassword";
    string domain = "MyDomain";

    string reportURL="http://ServerName/ReportServer?/ReportsFolder/ReportName&Parameter=UserName&rs:Command=Render&rs:Format=PDF";

    NetworkCredential nwc = new NetworkCredential(userid, password, domain);

    WebClient client = new WebClient();
    client.Credentials = nwc;

    Byte[] pageData = client.DownloadData(reportURL);

    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
    Response.BinaryWrite(pageData);
    Response.Flush();
    Response.End();

    //return View();
    }

This is a bit simple and will require a bit of fixing to pass something decent to a view in MVC

public ActionResult Index()
{
    /*Credentials of a user that has access to SSRS*/
    string userid = "UserId";
    string password = "MyPassword";
    string domain = "MyDomain";

    string reportURL="http://ServerName/ReportServer?/ReportsFolder/ReportName&Parameter=UserName&rs:Command=Render&rs:Format=PDF";

    NetworkCredential nwc = new NetworkCredential(userid, password, domain);

    WebClient client = new WebClient();
    client.Credentials = nwc;

    Byte[] pageData = client.DownloadData(reportURL);

    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + DateTime.Now);
    Response.BinaryWrite(pageData);
    Response.Flush();
    Response.End();

    //return View();
    }
滥情空心 2024-10-09 01:12:27

一个简单的解决方案是将 iframe 添加到您的 MVC 视图,该视图从报告服务 Web 服务打开您想要的报告。 iframe 将与报告服务的组件一起全面运行。如果您想将组件移至 MVC 视图中,则还可以动态控制 iframe 中的 url 使用的参数(例如使用 ajax)。

尽管这可行,但您仍然需要登录 Web 报告服务(iframe 将打开登录对话框)。对于 IE,这是通过使用 Windows 登录凭据“自动”完成的。

A simple solution is to add an iframe to your MVC view that opens the report you want from the reporting services web service. The iframe will be fully operational with the components from reporting services. The parameters used for the url in the iframe can also be controlled dynamically (e.g. with ajax) if you want to move the components out into your MVC view.

Although this works, you will still have to sign in to the web reporting service (the iframe will open a logon dialog). For IE this is "automagically" done though using your windows logon credentials.

我的鱼塘能养鲲 2024-10-09 01:12:27

您可以使用 ReportViewerForMvc 在 MVC 中查看报告,方法是使用 Nuget 安装它

Install-Package Microsoft.Report.Viewer -Version 11.0.0

Install-Package Microsoft.ReportViewer.Runtime.WebForms -Version 12.0.2402.15

Install-Package ReportViewerForMvc

一旦您安装了 ReportViewer 和其他必需的 Nuget 包(如上所示),请在 Visual Studio 项目中添加一个新的 Report.rdlc

在此处输入图像描述

添加数据集在上面创建的report.rdlc中

现在,在MVC中创建一个ActionMethod,它将从数据库查询数据并返回report

 SSRSInMVC.Report.Report ds = new SSRSInMVC.Report.Report();
    public ActionResult ReportStudent()
    {
        ReportViewer reportViewer = new ReportViewer();
        reportViewer.ProcessingMode = ProcessingMode.Local;
        reportViewer.SizeToReportContent = true;
        reportViewer.Width = Unit.Percentage(900);
        reportViewer.Height = Unit.Percentage(900);

        var connectionString = ConfigurationManager.ConnectionStrings["SSRSInMVC.Properties.Settings.StudentsConnectionString"].ConnectionString;


        SqlConnection conx = new SqlConnection(connectionString);
        SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Student_details", conx);

        adp.Fill(ds, ds.Student_details.TableName);

        reportViewer.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Report\Report1.rdlc";
        reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds.Tables[0]));


        ViewBag.ReportViewer = reportViewer;

        return View();
    }

视图中,您有如下代码就

@using ReportViewerForMvc;
@{
   ViewBag.Title = "Report Student";
 }
 <br/>
<br />

   @Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)

这样,我们就完成了。

参考:https: //qawithexperts.com/article/asp.net/displaying-ssrs-sql-server-reporting-service-in-mvc-view/77

You can view report in MVC using ReportViewerForMvc, by installing it using Nuget

Install-Package Microsoft.Report.Viewer -Version 11.0.0

Install-Package Microsoft.ReportViewer.Runtime.WebForms -Version 12.0.2402.15

Install-Package ReportViewerForMvc

Once you have installed the ReportViewer and other required Nuget packages as showed above, Add a new Report.rdlc in your Visual Studio project

enter image description here

Add dataset in the above created report.rdlc

Now, create a ActionMethod in MVC, which will query data from database and return report

 SSRSInMVC.Report.Report ds = new SSRSInMVC.Report.Report();
    public ActionResult ReportStudent()
    {
        ReportViewer reportViewer = new ReportViewer();
        reportViewer.ProcessingMode = ProcessingMode.Local;
        reportViewer.SizeToReportContent = true;
        reportViewer.Width = Unit.Percentage(900);
        reportViewer.Height = Unit.Percentage(900);

        var connectionString = ConfigurationManager.ConnectionStrings["SSRSInMVC.Properties.Settings.StudentsConnectionString"].ConnectionString;


        SqlConnection conx = new SqlConnection(connectionString);
        SqlDataAdapter adp = new SqlDataAdapter("SELECT * FROM Student_details", conx);

        adp.Fill(ds, ds.Student_details.TableName);

        reportViewer.LocalReport.ReportPath = Request.MapPath(Request.ApplicationPath) + @"Report\Report1.rdlc";
        reportViewer.LocalReport.DataSources.Add(new ReportDataSource("DataSet1", ds.Tables[0]));


        ViewBag.ReportViewer = reportViewer;

        return View();
    }

In the view, you have code as below

@using ReportViewerForMvc;
@{
   ViewBag.Title = "Report Student";
 }
 <br/>
<br />

   @Html.ReportViewer(ViewBag.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)

That's it, we are done.

Reference: https://qawithexperts.com/article/asp.net/displaying-ssrs-sql-server-reporting-service-in-mvc-view/77

甜味超标? 2024-10-09 01:12:27

为了以防万一它对任何人有帮助,我发现这些视频教程很容易遵循。
您只需忍受第一个视频中可怕的背景音乐即可。

ASP Net MVC 5 中的 SSRS 2019 报告

如何使用参数过滤 SSRS 2019 报告< /a>

我必须安装“ReportViewerForMvc14”而不是“ReportViewerForMvc”(视频中使用的),因为它不再可用。包装上的注释说它与原始版本相同,但只是更新为与 ReportViewer 14.0 配合使用。

Just in case it helps anybody, these video tutorials are what I found to be easy to follow.
(You just have to tolerate the horrible background music in the first video.)

SSRS 2019 Report in ASP Net MVC 5

How To Filter SSRS 2019 Report Using Parameter

I had to install "ReportViewerForMvc14" instead of "ReportViewerForMvc" (which was used in the video), because it is not available anymore. The note on the package says it is the same as the original but just updated to work with ReportViewer 14.0.

回眸一遍 2024-10-09 01:12:27

我在 asp.net mvc 中设置 ssrs 报告时遇到了很多问题。希望这个解决方案有帮助。我在后面的代码中使用 vb 作为编程语言。

注意:这是设置 ssrs 报告服务器端。假设 ssrs 报告已发布在远程 ssrs 服务器上。

  1. 将reportviewer包安装到您的解决方案中。
    我正在使用 nuget 包管理器控制台来设置解决方案所需的依赖文件。我已经为我的解决方案安装了 ReportViewerForMvc14,并且正在使用 .net Framework 4.7.2(如下面的屏幕截图所示)

注意:- Install-Package ReportViewerForMVC 不起作用..我已经包含了 14在最后 。

转到工具--> Nuget 包管理器 -->包管理器控制台-->选择默认的Project -->运行命令“Install-Package ReportViewerForMvc14”。

输入图片这里的描述

  1. 上面的命令将添加解决方案所需的支持文件、dll。安装后还要检查“ReportViewerForMvc”是否已添加到引用中。

  2. 在控制器中包含以下代码片段。设置报表查看器的所有属性后,我将报表查看器内容存储在 viewbag 中

    
    Function Index() As ActionResult
        'Fetch ssrs report server url and case history folder path entries from config.
        Dim ssrsReportServerUrl As String = ConfigurationManager.AppSettings.Get("SSRSReportURL") 
        Dim caseHistoryFolderPath As String = ConfigurationManager.AppSettings.Get("SSRSCaseHistoryReportPath")
        Dim qsCaseId As String = "CaseID"
        Dim CaseId As Integer = 0
        If String.IsNullOrWhiteSpace(Request.QueryString(qsCaseId)) Then
            Throw New ArgumentNullException("Page did not receive Case Id parameter.")
        End If
        If Not String.IsNullOrWhiteSpace(Request.QueryString(qsCaseId)) Then
            CaseId = Request.QueryString(qsCaseId).ToString
        End If

        If Not String.IsNullOrEmpty(ssrsReportServerUrl) AndAlso Not String.IsNullOrEmpty(caseHistoryFolderPath) Then
            Dim reportViewer As New ReportViewer
            reportViewer.ProcessingMode = ProcessingMode.Remote

            'Assign the reportserver url And path
            reportViewer.ServerReport.ReportServerUrl = New Uri(ssrsReportServerUrl)
            reportViewer.ServerReport.ReportPath = caseHistoryFolderPath

            'Assign the input parameters to report.--add multiple parameters below if you have multiple..i have only one parameter to pass.
            'to show the input parameter textbox entry on the screen , set below property to true.
            Dim rptParameters As New Microsoft.Reporting.WebForms.ReportParameter
            Dim paramarr(0) As Microsoft.Reporting.WebForms.ReportParameter
            rptParameters = New Microsoft.Reporting.WebForms.ReportParameter("CaseID", CaseId, False)
            paramarr(0) = rptParameters
            reportViewer.ServerReport.SetParameters(paramarr)

            '//Set the report properties (width, zoom, refresh, print controls)
            reportViewer.SizeToReportContent = True
            reportViewer.ZoomMode = ZoomMode.FullPage
            reportViewer.AsyncRendering = False
            reportViewer.ShowBackButton = False
            reportViewer.ShowRefreshButton = True
            reportViewer.ShowFindControls = True
            reportViewer.ShowPageNavigationControls = True
            reportViewer.ShowPrintButton = True

            reportViewer.ShowZoomControl = True

            reportViewer.ServerReport.Refresh()
            ViewBag.ReportViewer = reportViewer
        Else
            Throw New ArgumentNullException("Report Server URL or the Report Path is Invalid.")
        End If

        Return View(VIEW_FILE, ViewModel)
    End Function
  1. 在页面的视图部分包含以下代码片段。我正在使用 vbhtml 页面。我正在获取reportviewer viewbag 并显示在vbhtml 页面中进行显示。
@Imports ReportViewerForMvc


@Code
    ViewData("Title") = "Details"

End Code

    html, body {
        margin: 0;
        padding: 0;       
    }
    .myreport{
        background-color:#fff;
    }

@If Not ViewBag.ReportViewer 那么什么都不是 @ @Html.ReportViewer(TryCast(ViewBag.ReportViewer, Microsoft.Reporting.WebForms.ReportViewer), New With {.htmlAttributes = New With {.width = "100%", .height = "100%", .scrolling = "no “}})

结束如果

I have faced a lot of issues setting up the ssrs reports in asp.net mvc . Hope this solution helps. i'm using vb as programming language in the code behind.

Note: This is setting up ssrs report server side. Assuming ssrs report is already published on the remote ssrs server.

  1. Installing reportviewer package on to your solution.
    I'm making use of nuget package manager console for setting up the dependent files required for the solution. I have installed ReportViewerForMvc14 for my solution and i'm using .net framework 4.7.2 (as shown in the screenshot below)

Note:- Install-Package ReportViewerForMVC didn't work ..I had included 14 at the end .

Go to Tools--> Nuget Package Manager --> Package Manager Console--> Select the default Project --> Run the command 'Install-Package ReportViewerForMvc14'.

enter image description here

  1. The above command will add the supporting files , dlls needed for the solution. Also after installing check 'ReportViewerForMvc' is added onto the references.

  2. Including the below code snippet in the controller. After setting all the properties of the report viewer, i'm storing the report viewer content in viewbag

    
    Function Index() As ActionResult
        'Fetch ssrs report server url and case history folder path entries from config.
        Dim ssrsReportServerUrl As String = ConfigurationManager.AppSettings.Get("SSRSReportURL") 
        Dim caseHistoryFolderPath As String = ConfigurationManager.AppSettings.Get("SSRSCaseHistoryReportPath")
        Dim qsCaseId As String = "CaseID"
        Dim CaseId As Integer = 0
        If String.IsNullOrWhiteSpace(Request.QueryString(qsCaseId)) Then
            Throw New ArgumentNullException("Page did not receive Case Id parameter.")
        End If
        If Not String.IsNullOrWhiteSpace(Request.QueryString(qsCaseId)) Then
            CaseId = Request.QueryString(qsCaseId).ToString
        End If

        If Not String.IsNullOrEmpty(ssrsReportServerUrl) AndAlso Not String.IsNullOrEmpty(caseHistoryFolderPath) Then
            Dim reportViewer As New ReportViewer
            reportViewer.ProcessingMode = ProcessingMode.Remote

            'Assign the reportserver url And path
            reportViewer.ServerReport.ReportServerUrl = New Uri(ssrsReportServerUrl)
            reportViewer.ServerReport.ReportPath = caseHistoryFolderPath

            'Assign the input parameters to report.--add multiple parameters below if you have multiple..i have only one parameter to pass.
            'to show the input parameter textbox entry on the screen , set below property to true.
            Dim rptParameters As New Microsoft.Reporting.WebForms.ReportParameter
            Dim paramarr(0) As Microsoft.Reporting.WebForms.ReportParameter
            rptParameters = New Microsoft.Reporting.WebForms.ReportParameter("CaseID", CaseId, False)
            paramarr(0) = rptParameters
            reportViewer.ServerReport.SetParameters(paramarr)

            '//Set the report properties (width, zoom, refresh, print controls)
            reportViewer.SizeToReportContent = True
            reportViewer.ZoomMode = ZoomMode.FullPage
            reportViewer.AsyncRendering = False
            reportViewer.ShowBackButton = False
            reportViewer.ShowRefreshButton = True
            reportViewer.ShowFindControls = True
            reportViewer.ShowPageNavigationControls = True
            reportViewer.ShowPrintButton = True

            reportViewer.ShowZoomControl = True

            reportViewer.ServerReport.Refresh()
            ViewBag.ReportViewer = reportViewer
        Else
            Throw New ArgumentNullException("Report Server URL or the Report Path is Invalid.")
        End If

        Return View(VIEW_FILE, ViewModel)
    End Function
  1. Include the below code snippet in the view section of your page. I'm using vbhtml page . I'm getting the reportviewer viewbag and displaying in the vbhtml page for display.
@Imports ReportViewerForMvc


@Code
    ViewData("Title") = "Details"

End Code

    html, body {
        margin: 0;
        padding: 0;       
    }
    .myreport{
        background-color:#fff;
    }

@If Not ViewBag.ReportViewer Is Nothing Then @ @Html.ReportViewer(TryCast(ViewBag.ReportViewer, Microsoft.Reporting.WebForms.ReportViewer), New With {.htmlAttributes = New With {.width = "100%", .height = "100%", .scrolling = "no"}})

End If

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文