logo
small logo
  • Producto
  • Comprar
  • Ayuda
  • Blogs
  • Consola de usarios Ayuda
    • en
    • pt
    • es
    • de
    • pl
    • JP
    • ZH
  • Página principal
  • /
  • Blogs
  • /
  • Cómo pasar una lista de parámetros a un informe web FastReport.Net
  • Cómo hacer herencia de informes en FastReport .NET

    29 de enero de 2021

    Cuando tiene la tarea de crear una gran cantidad de informes dentro de un estilo

    read more
  • Cómo establecer mediante programación la configuración predeterminada del cliente de correo electrónico para enviar correos electrónicos desde FastReport.NET

    12 de febrero de 2021

    Como muchos otros generadores de informes, FastReport .NET le permite enviar un informe por correo

    read more
  • Cómo crear y generar códigos de barras ITF-14 en aplicaciones .NET

    25 de febrero de 2021

    ITF-14 (Interleaved Two of Five) es un código numérico de dos bandas, también conocido como

    read more
  • Cómo actualizar el informe web FastReport.Core

    21 de septiembre de 2020

    A veces es necesario actualizar el informe, por ejemplo, si ingresa un nuevo valor de

    read more
  • Informes y documentos PDF en Blazor

    5 de abril de 2021

    Microsoft ha lanzado recientemente una plataforma web llamada Blazor. Este marco permite crear una interfaz

    read more

Cómo pasar una lista de parámetros a un informe web FastReport.Net

15 de abril de 2020

A la hora de crear un informe a menudo tiene que pasar algunos valores a ellos desde fuera. Lo necesita para filtrar datos en el informe o para controlar la lógica de este. Em mi práctica de utilizar FastReport .Net a menudo me enfrento con esta necesidad. Ya que generalmente trabajo con los informes web, paso los parámetros con un url. Por lo general, mi informes son bastante complejos y tienen más de un parámetro. Por lo cual tengo que pasar una lista de parámetros, es decir, una lista de conjuntos de valores clave donde "clave" es el nombre del parámetro.

Entenderlo todo será más fácil en un ejemplo. En este caso utilizo una aplicación ASP.Net Core Web Api.

 
1 2 3 4 5 6 7 8 9 10 
namespace ParametersWeb.Models {  public class Reports  {  // Report ID  public int Id { get; set; }  // Report File Name  public string ReportName { get; set; }  } }

 ValuesController:

Fill the array of reports:

1 2 3 4 5 
Reports[] reportItems = new Reports[]  {  new Reports { Id = 1, ReportName = "Parameters.frx" },  new Reports { Id = 2, ReportName = "Master-Detail.frx" }   };

 El método de crear informe es asincrónico porque utiliza un método asincrónico de convertir informe en el formato HTML. Necesitamos este formato para mostrar el informe en el navegador:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 
[HttpGet("{id}")]  public async System.Threading.Tasks.Task<IActionResult> GetAsync(int id)  {  string mime = "application/html"; // MIME header with default value  // Find report  var parameters = HttpContext.Request.QueryString.ToString().Substring(1);  Reports reportItem = reportItems.FirstOrDefault((p) => p.Id == id); // we get the value of the collection by id  if (reportItem != null)  {  string webRootPath = _hostingEnvironment.WebRootPath; // determine the path to the wwwroot folder  string reportPath = (webRootPath + "/App_Data/" + reportItem.ReportName); // determine the path to the report  string dataPath = (webRootPath + "/App_Data/nwind.xml");// determine the path to the database  using (MemoryStream stream = new MemoryStream()) // Create a stream for the report  {  try  {  using (DataSet dataSet = new DataSet())  {  // Fill the source by data  dataSet.ReadXml(dataPath);  // Turn on web mode FastReport  Config.WebMode = true;   WebReport webReport = new WebReport();//create the report object  webReport.Report.Load(reportPath); //upload the report  webReport.Report.RegisterData(dataSet, "NorthWind"); //register the data sourcw in the report  if (parameters != null)  {  string[] parameterList = parameters.Split(',');  foreach (string item in parameterList)  {  string[] parameter = item.Split('=');  webReport.Report.SetParameterValue(parameter[0], parameter[1]); //set the report parameter value  }  }  // inline registration of FastReport javascript  webReport.Inline = true;//allow to register scripts and styles in HTML-body intead of putting them in the header  HtmlString reportHtml = await webReport.Render(); //upload the report in HTML  byte[] streamArray = Encoding.UTF8.GetBytes(reportHtml.ToString());  stream.Write(streamArray, 0, streamArray.Length);//write down the report in the stream   }  // Get the name of the resulting report file with the necessary extension   var file = String.Concat(Path.GetFileNameWithoutExtension(reportPath), ".", "html");   return File(stream.ToArray(), mime, file); // attachment  }  // Handle exceptions  catch  {  return new NoContentResult();  }  finally  {  stream.Dispose();  }  }  }  else  return NotFound();  }

 La escencia de este método es que cargamos el modelo de informe seleccionado, parseamos parámetros desde el URL y pasamos sus valores al informe.  Después transformamos un informe e el formato HTML y devolvemos el archivo al cliente.

Los nombres de los parámetros que pasa al informe tienen que corresponder a los parámetros del informe:

 

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 
<!DOCTYPE html> <html> <head>  <title></title>  <meta charset="utf-8" />  <script src="/lib/jquery/dist/jquery.min.js"></script> </head> <body>  <script>  function call() {  $.ajax({  type: "GET",  url: "api/values/1?FirstParameter=Value1,SecondParameter=Value2",  //contentType: "application/text; charset=utf-8",  dataType: "html",  success: function (data) {  $('#results').html(data);  console.log(data);  }, //End of AJAX Success function  failure: function (data) {  alert(data.responseText);  }, //End of AJAX failure function  error: function (data) {  alert(data.responseText);  } //End of AJAX error function  });  };  </script>  <form method="GET" id="formx" action="javascript:void(null);" onsubmit="call()">  <input value="Show" type="submit">  </form>  <div id="results" typeof="submit"></div><!—here will be the result--> </body> </html>

 

 

about product descargar comprar
avatar
Dmitriy Fedyashov
Technical Writer
Fast Reports Team: Dmitriy Fedyashov - Technical Writer at Fast Reports
.NET FastReport

Add comment
logo
  • 800-985-8986 (English, US)
  • +4930568373928 (German)
  • +55 19 98147-8148 (Portuguese)
  • info@fast-report.com
  • 901 N Pitt Str #325 Alexandria VA 22314
  • Comprar
  • Descargar
  • Documentación
  • Opiniones de usuarios
  • Cómo desinstalar nuestros productos
  • Enviar mensaje
  • FAQ
  • Toturial en vídeo
  • Foro
  • Documentación técnica
  • Nuestras noticias
  • Quiénes somos
  • Socios
  • Contactos

© 1998-2022 by Fast Reports Inc.

  • Privacidad