1

Como criar ReportViewer no Asp.Net Mvc 4 ? O Relatório está feito, só preciso criar o ReportViewer com as opções de exportar pdf, excel e word.

Exemplo:

 <rsweb:ReportViewer ID="ReportViewer1" runat="server" Font-Names="Verdana" Font-Size="8pt" Height="100%" WaitMessageFont-Names="Verdana" WaitMessageFont-Size="14pt" Width="100%">
            <LocalReport ReportEmbeddedResource="NFSWeb.ListagemRPS.rdlc">
                <DataSources>
                    <rsweb:ReportDataSource DataSourceId="ObjectDataSource1" Name="DsRPS" />
                </DataSources>
            </LocalReport>
        </rsweb:ReportViewer>

Como posso fazer isso igual do webforms em mvc ?

1

2 Respostas 2

3

você precisa para criar uma view como ReportView.ascx (isso mesmo, webform) e, em seguida, você precisa criar uma report view model, por favor, dê uma olhada.

View: ReportViewer.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ReportViewerControl.ascx.cs" Inherits="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 style="Height:720px;Width:800px">
    <asp:ScriptManager ID="scriptManager" runat="server" ScriptMode="Release" EnablePartialRendering="false" />
    <rsweb:ReportViewer Width="100%" Height="100%" ID="reportViewer" ShowPrintButton="true" KeepSessionAlive="true" runat="server" AsyncRendering="false" ProcessingMode="Remote">
         <ServerReport />
    </rsweb:ReportViewer>
</div>
</form>

no code behind: ReportViewer.ascx.cs

namespace 
{
    public partial class ReportViewerControl : System.Web.Mvc.ViewUserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            // Required for report events to be handled properly.
            //reportViewer.ServerReport.ReportServerCredentials = new ReportServerCredentials();
            Context.Handler = Page;

        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {                
                ReportingServicesReportViewModel model = (ReportingServicesReportViewModel)Model;
                reportViewer.ServerReport.ReportServerCredentials = model.ServerCredentials;
                ReportParameter[] RptParameters = model.parameters;

                reportViewer.ServerReport.ReportPath = model.ReportPath;
                reportViewer.ServerReport.ReportServerUrl = model.ReportServerURL;                

                if(RptParameters.Count() > 0)
                this.reportViewer.ServerReport.SetParameters(RptParameters);
                this.reportViewer.ServerReport.Refresh();

            }            
        }
    }   
}

Você cria um outro arquivo para tratar as requisições ao report server: ReportingServiceViewModel.cs

public class ReportingServicesReportViewModel
    {
        #region Constructor
        public ReportingServicesReportViewModel(String reportPath,List<ReportParameter> Parameters)
        {
            ReportPath = reportPath;
            parameters = Parameters.ToArray();
        }
        public ReportingServicesReportViewModel()
        {           
        }
        #endregion Constructor

        #region Public Properties
        public ReportServerCredentials ServerCredentials { get { return new ReportServerCredentials(); } }
        public String ReportPath { get; set; }
        public Uri ReportServerURL { get { return new Uri(WebConfigurationManager.AppSettings["ReportServerUrl"]); } }
        public ReportParameter[] parameters { get; set; }
        private string UploadDirectory = HttpContext.Current.Server.MapPath("~/App_Data/UploadTemp/");
        private string TempDirectory = HttpContext.Current.Server.MapPath("~/tempFiles/");        
     }

Configura as credenciais: ReportServerCredentials.cs

[Serializable]
    public sealed class ReportServerCredentials : IReportServerConnection2//IReportServerCredentials
    {

        #region Private Properties
        private string _username;
        private string _password;
        private string _domain;
        #endregion Private Properties

        #region Public Properties
        public System.Security.Principal.WindowsIdentity ImpersonationUser
        {
            get { return null; }
        }

        public System.Net.ICredentials NetworkCredentials
        {
            get { return new NetworkCredential(_username, _password, _domain); }
        }
        #endregion Public Properties

        #region Constructor
        public ReportServerCredentials(string userName, string password, string domain)
        {
            _username = userName;
            _password = password;
            _domain = domain;
        }
        public ReportServerCredentials()
        {
            var appSetting = WebConfigurationManager.AppSettings;
            _username = appSetting["ReportServerUser"];
            _password = appSetting["ReportServerPassword"];
            _domain = appSetting["ReportServerDomain"];
        }
        #endregion Constructor

        #region Public Method
        public bool GetFormsCredentials(out System.Net.Cookie authCookie, out string userName, out string password, out string authority)
        {
            authCookie = null;
            userName = null;
            password = null;
            authority = null;
            return false;
        }
        #endregion Public Method


        public IEnumerable<Cookie> Cookies { get { return null; } }


        public IEnumerable<string> Headers { get { return null; } }

        public Uri ReportServerUrl { get { return new Uri(WebConfigurationManager.AppSettings["ReportServerUrl"]); } }

        public int Timeout { get { return 60000; } }
    }

Você pode usar esse controller para chamar uma nova view que você vai criar: HomeController.cs

public class HomeController
{
    public ActionResult ActionReport(int Id)
    {
      ReportingServicesReportViewModel model = new ReportingServicesReportViewModel(
      "ReportPath",
      new List<Microsoft.Reporting.WebForms.ReportParameter>()
      { 
        new Microsoft.Reporting.WebForms.ReportParameter("parameter1",Id.ToString(),false) 
                });
            return View("ViewReport", model);
        }
}

Aqui é a view que esse controller deve apontar: ViewReport.cshtml

@model ReportingInfrastructure.ReportingServicesReportViewModel
<div style="display: table; width: 100%;">

    @{

        @Html.Partial("ReportViewerControl", Model)

    }
</div>

Pronto, agora é só fazer uma chamada para o controller e deve funcionar.

2

Estou supondo que você já instalou no seu projeto o pacote NuGet MvcReportViewer.

Os passos para configuração e uso estão aqui.

Exemplos para configuração do Controller estão aqui.

Os respectivos exemplos para Views estão aqui.

6
  • Sim, Instalei o pacote. Vou ver, valeu.
    – AndreeH
    9/09/2015 às 20:21
  • cara, só preciso criar o report igual no webforms na minha view, mas em mvc. Como posso fazer isso em mvc ? Reformulei a pergunta.
    – AndreeH
    10/09/2015 às 17:17
  • @AndreeH Você chegou a ler os exemplos? 10/09/2015 às 17:36
  • cheguei mas achei um pouco complexo, e tentei aqui e a view não tá reconhecendo a referencia do MvcReportViewer.
    – AndreeH
    10/09/2015 às 17:41
  • Significa que faltou configuração. Abra outra pergunta e explique essa dificuldade. 10/09/2015 às 17:42

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .