2011-11-03 175 views
10

Me gustaría presentar un informe RDLC en HTML dentro de un proyecto ASP.NET MVC.Renderizar un informe RDLC en HTML en ASP.NET MVC

Realicé con éxito un prototipo que representa un informe RDLC en PDF, Excel e imagen TIFF, con la ayuda de this article. Pero me sorprendió que HTML no sea uno de los formatos disponibles por defecto en LocalReport.Render().

me encontré con this article, que describe un truco para que el formato de representación de HTML4.0, pero creo que es sólo para un control ReportViewer (puedo estar equivocado sin embargo).

La pregunta es, ¿en MVC cómo hacer un informe RDLC en HTML como lo hace un ReportView (ver la captura de pantalla a continuación)?

An RDLC report rendered in a ReportView control

+0

También estoy tratando de lograr esto, pero mi problema es que no pude encontrar "mostrar fuentes de datos" en el menú de datos. ¿Podrían por favor guiar en ese – Tassadaque

+0

? Terminé usando el "Asistente de informes" en su lugar. –

+0

ServerReport.Render() admite "HTML4.0" pero LocalReport.Render() no –

Respuesta

5

Usted puede utilizar el objeto de ReportViewer para rendir RDLC a PDF o HTML. En mi caso (a continuación), quería un documento PDF y lo devolví como un FileContentResult ActionResult. Si desea que regrese como descarga, use File ActionResult (lo comenté para su uso).

public ActionResult GetPackingSlipPDF(int shipmentId) 
    { 
     var shipment = _inboundShipmentService.GetInboundShipmentById(shipmentId); 

     Warning[] warnings; 
     string mimeType; 
     string[] streamids; 
     string encoding; 
     string filenameExtension; 

     var viewer = new ReportViewer(); 
     viewer.LocalReport.ReportPath = @"Labels\PackingSlip.rdlc"; 

     var shipLabel = new ShippingLabel { ShipmentId = shipment.FBAShipmentId, Barcode = GetBarcode(shipment.FBAShipmentId) }; 

     viewer.LocalReport.DataSources.Add(new ReportDataSource("ShippingLabel", new List<ShippingLabel> { shipLabel })); 
     viewer.LocalReport.Refresh(); 

     var bytes = viewer.LocalReport.Render("PDF", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings); 

     return new FileContentResult(bytes, mimeType); 

     //return File(bytes, mimeType, shipment.FBAShipmentId + "_PackingSlip.pdf"); 
    } 
+2

Esto genera un PDF: el OP necesita un documento HTML. 'LocalReport.Render()' no es compatible con HTML en ReportViewer 2010. –

1

pongo este proyecto juntos hace mucho tiempo http://mvcrdlc.codeplex.com/

De memoria no debería ser un HTML render de la rdlc, así como el PDF

+1

Solo hay representación de Excel y PDF en el repositorio vinculado. –

13

Ésta es una tarea sencilla. Puedes seguir los siguientes pasos.

  1. Crea una carpeta en tu solución y dale un nombre Informes.
  2. Agregue un formulario web ASP.Net y llámelo como ReportView.aspx
  3. Cree un Informe de clase y añádalo a la carpeta Informes. Agregue el siguiente código a la clase.

    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; } 
    } 
    
  4. Añadir otra Clase y la llamó ReportBasePage.cs. Agregue el siguiente código en esta clase.

    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); 
           } 
          } 
         } 
        } 
    } 
    
  5. Agregue ScriptManager a la página ReportView.aspx. Ahora lleve un Visor de informes a la página. En el visor de informes establezca la propiedad AsyncRendering = "false". El código se da a continuación.

    <rsweb:ReportViewer ID="ReportViewerRSFReports" runat="server" AsyncRendering="false" 
        Width="1271px" Height="1000px" > 
    </rsweb:ReportViewer> 
    
  6. añadir dos NameSpace en ReportView.aspx.cs

    using Microsoft.Reporting.WebForms; 
    using System.IO; 
    
  7. Cambiar el System.Web.UI.Page a ReportBasePage. Simplemente reemplace su código usando lo siguiente.

    public partial class ReportView : ReportBasePage 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
         if (!IsPostBack) 
         { 
          RenderReportModels(this.ReportDataObj); 
         } 
        } 
    
        private void RenderReportModels(ReportData reportData) 
        { 
         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(); 
        } 
    } 
    
  8. Agregue una carpeta a la Carpeta de Informes y llámela Informe. Ahora agregue un informe RDLC a la carpeta Informes/Informe y lo llamó ClosingInventory.rdlc.

  9. Ahora agregue un controlador y asígnele el nombre ReportController. En el controlador, agregue el siguiente método de acción.

    public ActionResult ReportViewer() 
    {     
        ViewData["reportUrl"] = "../Reports/View/local/ClosingInventory/"; 
    
        return View(); 
    } 
    
  10. Agregar una página de vista, haga clic en el controlador ReportViewer. Nombrado la página de vista ReportViewer.cshtml. Agregue el siguiente código a la página de visualización.

    @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" /> 
    
        } 
    
  11. Añadir un iframe. Establecer la propiedad del marco flotante de la siguiente manera

    frameborder="0" width="1000"; height="1000"; style="overflow:hidden;" scrolling="no" 
    
  12. Agregar Siguiendo JavaScript para el espectador.

    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; 
    } 
    
  13. En el archivo Web.config agregue la siguiente clave a la sección de appSettings añadir

    key="UnobtrusiveJavaScriptEnabled" value="true" 
    
  14. En manipuladores System.Web Sección añada la siguiente clave

    añadir verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

  15. Cambia tu origen de datos como propio. Esta solución es muy simple y creo que todos la disfrutan.

Cuestiones relacionadas