In questo articolo verrà illustrato come è possibile utilizzare la libreria Chart.js per costruire sorprendenti report in HTML5 utilizzando jQuery e ASP.NET e come è possibile salvare l’immagine del report generato.
Chart.js utilizza l’elemento <canvas> di HTML5, che è supportato da tutti i moderni browser, e da la possibilità di visualizzare i dati in 6 modi diversi, in modo animato, con diverse opzioni di personalizzazione ed estensioni interattive.
Nell’esempio seguente verrà utilizzato il grafico di tipo Radar che darà in output la seguente immagine:
I dati necessari al report vengono richiesti al server con una chiamata jQuery AJAX ad un Web Method esposto mediante .NET con la seguente funziona Javascript:
function GetReport() { var filterByName = "fiter value"; $.ajax({ type: "POST", url: "Default.aspx/GetReportData", data: '{name: "' + filterByName + '" }', contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { var reportData = JSON.parse(response.d); var reportObj = document.getElementById("canvas"); window.myRadar = new Chart(reportObj.getContext("2d")).Radar(reportData, { responsive: true }); }, error: function (msg) { alert(msg); } }); }
Il Web Method lato server, restituisce i dati serializzati in formato JSON:
[WebMethod] public static string GetReportData(string name) { var result = GetDataFromDatabase(); return new JavaScriptSerializer().Serialize(result); }
Infine, viene data la possibilità di salvare il report come immagine (png) con la seguente funzione lato client:
function SaveReport() { var image = document.getElementById("canvas").toDataURL("image/png"); image = image.replace('data:image/png;base64,', ''); $.ajax({ type: 'POST', url: '/Default.aspx/SaveReport', data: '{ "imageData" : "' + image + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { alert('Image saved!'); } }); }
e con il seguente Web Method lato server:
[WebMethod] public static void SaveReport(string imageData) { //Server.MapPath string path = HttpContext.Current.Server.MapPath("SavedReports") + "\\report.png"; FileStream fs = new FileStream(path, FileMode.Create); BinaryWriter bw = new BinaryWriter(fs); byte[] data = Convert.FromBase64String(imageData); bw.Write(data); bw.Close(); }
Scarica l’esempio completo di HTML5 Chart JS on ASP.NET and jQuery with export canvas image sviluppato con Visual Studio 2013.