如何在Razor中使用ReportViewer控件?

问题描述:

我见过很多人说要使用iframe或新页面来显示ReportViewer控件.有没有一种方法可以在不使用iframe的情况下与页面的其余部分内联显示?

I've seen many people saying to use an iframe or a new page to display a ReportViewer control. Is there a way to display the control inline with the rest of my page without using an iframe?

如果Razor继承自System.Web.Mvc.ViewUserControl,则可以将.ascx用户控件用作Razor的部分视图.

You can use .ascx user controls as partial views with Razor if they inherit from System.Web.Mvc.ViewUserControl.

在这种情况下,您可以创建一个ASCX,该ASCXView\Controller文件夹中包含ReportViewer控件和必需的ScriptManager:

In this instance, you can create an ASCX that contains your ReportViewer control and the requisite ScriptManager in your View\Controller folder:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ReportViewerControl.ascx.cs" Inherits="MyApp.Views.Reports.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">
<div>
    <asp:ScriptManager ID="scriptManager" runat="server" EnablePartialRendering="false" />
    <rsweb:ReportViewer Width="100%" Height="100%" ID="reportViewer" runat="server" AsyncRendering="false" ProcessingMode="Remote"> 
        <ServerReport />
    </rsweb:ReportViewer> 
</div>
</form>

在后面的代码中,请确保在Page_Init中包括以下内容;否则,您将无法在报告视图中使用任何选项:

In the code-behind, make sure to include the following in the Page_Init; otherwise, you won't be able to use any options in the report view:

protected void Page_Init(object sender, EventArgs e)
{
    // Required for report events to be handled properly.
    Context.Handler = Page;
}

您还希望确保控件继承自System.Web.Mvc.ViewUserControl:

You also want to make sure that your control inherits from System.Web.Mvc.ViewUserControl:

public partial class ReportViewerControl : ViewUserControl

要使用此控件,您可以在剃刀"页面中执行以下操作:

To use this control, you would do something like this in your Razor page:

@Html.Partial("ReportViewerControl", Model)

然后,您可以像往常一样在控件的Page_Load中设置ReportViewer.您将有权访问名为Modelobject,可以将其转换为要发送的模型的类型,然后使用:

You can then setup your ReportViewer in the Page_Load of the control as you normally would. You will have access to an object named Model, which you can cast to the type of the model that you send in and then use:

ReportViewParameters model = (ReportViewParameters)Model;