How can I use a ReportViewer control with Razor?

2020-07-16 02:40发布

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?

1条回答
Lonely孤独者°
2楼-- · 2020-07-16 03:02

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

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>

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;
}

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)

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;
查看更多
登录 后发表回答