locked
How to integrate chartjs linear gauge and circular gauge in C# code in ASP.NET web application? RRS feed

  • Question

  • User-1313071134 posted

    I am trying to create a web application on ASP.NET which connects to the SQL server to create a dashboard. For the dashboard, I am using chartjs library. But now I decided to use the linear gauge chart and circular gauge chart. For example, for the circular gauge chart it is meant to be HTML and Javascript, so if I wanna included it in the .aspx file it should look like that:

    <!DOCTYPE html>
    <html lang="en-US">
    <head>
      <meta charset="utf-8">
      <meta http-equiv="X-UA-Compatible" content="IE=Edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Gauge Chart with datalabels plugin displaying labels</title>
      <script src="https://unpkg.com/chart.js@2.8.0/dist/Chart.bundle.js"></script>
      <script src="https://unpkg.com/chartjs-gauge@0.2.0/dist/chartjs-gauge.js"></script>
      <script src="https://unpkg.com/chartjs-plugin-datalabels@0.7.0/dist/chartjs-plugin-datalabels.js"></script>
    </head>
    
    <script>
    var randomScalingFactor = function() {
      return Math.round(Math.random() * 100);
    };
    
    var randomData = function () {
      return [
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor(),
        randomScalingFactor()
      ];
    };
    
    var randomValue = function (data) {
      return Math.max.apply(null, data) * Math.random();
    };
    
    var data = randomData();
    var value = randomValue(data);
    
    var config = {
      type: 'gauge',
      data: {
        labels: ['Success', 'Warning', 'Warning', 'Fail'],
        datasets: [{
          data: data,
          value: value,
          backgroundColor: ['green', 'yellow', 'orange', 'red'],
          borderWidth: 2
        }]
      },
      options: {
        responsive: true,
        title: {
          display: true,
          text: 'Gauge chart with datalabels plugin displaying labels'
        },
        layout: {
          padding: {
            bottom: 30
          }
        },
        needle: {
          // Needle circle radius as the percentage of the chart area width
          radiusPercentage: 2,
          // Needle width as the percentage of the chart area width
          widthPercentage: 3.2,
          // Needle length as the percentage of the interval between inner radius (0%) and outer radius (100%) of the arc
          lengthPercentage: 80,
          // The color of the needle
          color: 'rgba(0, 0, 0, 1)'
        },
        valueLabel: {
          display: false
        },
        plugins: {
          datalabels: {
            display: true,
            formatter:  function (value, context) {
              return context.chart.data.labels[context.dataIndex];
            },
            //color: function (context) {
            //  return context.dataset.backgroundColor;
            //},
            color: 'rgba(0, 0, 0, 1.0)',
            //color: 'rgba(255, 255, 255, 1.0)',
            backgroundColor: null,
            font: {
              size: 20,
              weight: 'bold'
            }
          }
        }
      }
    };
    
    window.onload = function() {
      var ctx = document.getElementById('chart').getContext('2d');
      window.myGauge = new Chart(ctx, config);
    };
    
    document.getElementById('randomizeData').addEventListener('click', function() {
      config.data.datasets.forEach(function(dataset) {
        dataset.data = randomData();
        dataset.value = randomValue(dataset.data);
      });
    
      window.myGauge.update();
    });
    </script>
    
    <body>
      <div id="canvas-holder" style="width:100%">
      <canvas id="chart"></canvas>
      </div>
      <button id="randomizeData">Randomize Data</button>
    </body>
    </html>

    How can I integrate this script in C# so I can select data from the SQL table and display them on the charts?

    I appreciate the help

    <script src="https://unpkg.com/chart.js@2.8.0/dist/Chart.bundle.js"></script> <script src="https://unpkg.com/chartjs-gauge@0.2.0/dist/chartjs-gauge.js"></script> <script src="https://unpkg.com/chartjs-plugin-datalabels@0.7.0/dist/chartjs-plugin-datalabels.js"></script>

    Wednesday, July 1, 2020 7:01 AM

Answers

  • User475983607 posted

    You need to learn JSON, JavaScript, chartjs, AJAX or fetch, and Web Web Methods.    Building a dynamic string is not a good approach.  You'll either build a JavaScript application that manages the chart or you'll build the chart using code blocks to populate the chart data on the server.

    Below are a few examples. 

    https://forums.asp.net/p/2129509/6169081.aspx

    https://forums.asp.net/t/2145924.aspx

    Example based on https://chart-js.com/documentation/charts/gauge-chart.php

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebFormsDemo.chartjs._default" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
            <div class="col-md-12 py-2">
            <span class="badge badge-dark">Chart-JS.com</span>
        </div>
        <div class="col-md-6 offset-md-3 my-5">
            <div class="card">
                <div class="card-body">
                    <h1 class="pt-3 text-center">Chart JS Gauge Chart</h1>
                    <hr>
                </div>
                <div class="card-body">
                    <canvas id="myChart"></canvas>
                </div>
            </div>
        </div>
    
        <!-- https://chart-js.com/documentation/charts/gauge-chart.php -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
        <script>
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            // The type of chart we want to create
            type: 'doughnut',
    
            // The data for our dataset
            data: <%= Newtonsoft.Json.JsonConvert.SerializeObject(Model)%>,
    
            // Configuration options go here
            options: {
                circumference: 1 * Math.PI,
                rotation: 1 * Math.PI,
                cutoutPercentage: 90
            }
        });
        </script>
    </asp:Content>
    
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo.chartjs
    {
       
        public partial class _default : System.Web.UI.Page
        {
            public ChartJsDataModel Model { get; set; }
            protected void Page_Load(object sender, EventArgs e)
            {
                Model = new ChartJsDataModel()
                {
                    labels = new string[] { "January", "February", "March", "April", "May" },
                    datasets = new Dataset[]
                     {
                         new Dataset()
                         {
                            backgroundColor = new string[] {"rgb(0, 99, 132)", "green", "red", "yellow", "orange" },
                            borderColor ="My First dataset",
                            label = "#fff",
                            data = new int[] { 5, 10, 5, 2, 20 }
                         }
                     }
                };
    
                var s = JsonConvert.SerializeObject(Model);
            }
        }
    
        public class ChartJsDataModel
        {
            public string[] labels { get; set; }
            public Dataset[] datasets { get; set; }
    
        }
    
        public class Dataset
        {
            public string label { get; set; }
            public string[] backgroundColor { get; set; }
            public string borderColor { get; set; }
    
            public int[] data { get; set; }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 2, 2020 11:11 AM

All replies

  • User348806598 posted

    You can simply do an ajax call to server and get the data. After that, you can initiate chart js

    Wednesday, July 1, 2020 6:11 PM
  • User-1313071134 posted

    Could you please elaborate more about this, like an example of how this can be done? I would appreciate that

    Thursday, July 2, 2020 3:44 AM
  • User1535942433 posted

    Hi samiarja,

    Accroding to your description and codes,As far as I think,you could use ajax to get the data from database and return data into gauge chart.

    More details,you could refer to below codes:

    <script>
            //var randomScalingFactor = function () {
            //    return Math.round(Math.random() * 100);
    
            //};
    
            var randomData = function () {
                $.ajax({
                    type: "POST",
                    url: "2168615.aspx/getTrafficSourceData",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess_,  
                });
                function OnSuccess_(response) {
                    var aData = response.d;
                    var arr = [];
                    $.each(JSON.parse(aData), function (inx, val) {
                        .....
                    });
                     return arr;
                }
                //return [
                //    randomScalingFactor(),
                //    randomScalingFactor(),
                //    randomScalingFactor(),
                //    randomScalingFactor()
                //];
            };
    
            var randomValue = function (data) {
                return Math.max.apply(null, data) * Math.random();
            };
    
            var data = randomData();
            var value = randomValue(data);
    
            var config = {
                type: 'gauge',
                data: {
                    labels: ['Success', 'Warning', 'Warning', 'Fail'],
                    datasets: [{
                        data: data,
                        value: value,
                        backgroundColor: ['green', 'yellow', 'orange', 'red'],
                        borderWidth: 2
                    }]
                },
                options: {
                    responsive: true,
                    title: {
                        display: true,
                        text: 'Gauge chart with datalabels plugin displaying labels'
                    },
                    layout: {
                        padding: {
                            bottom: 30
                        }
                    },
                    needle: {
                        // Needle circle radius as the percentage of the chart area width
                        radiusPercentage: 2,
                        // Needle width as the percentage of the chart area width
                        widthPercentage: 3.2,
                        // Needle length as the percentage of the interval between inner radius (0%) and outer radius (100%) of the arc
                        lengthPercentage: 80,
                        // The color of the needle
                        color: 'rgba(0, 0, 0, 1)'
                    },
                    valueLabel: {
                        display: false
                    },
                    plugins: {
                        datalabels: {
                            display: true,
                            formatter: function (value, context) {
                                return context.chart.data.labels[context.dataIndex];
                            },
                            //color: function (context) {
                            //  return context.dataset.backgroundColor;
                            //},
                            color: 'rgba(0, 0, 0, 1.0)',
                            //color: 'rgba(255, 255, 255, 1.0)',
                            backgroundColor: null,
                            font: {
                                size: 20,
                                weight: 'bold'
                            }
                        }
                    }
                }
            };
    
            window.onload = function () {
                var ctx = document.getElementById('chart').getContext('2d');
                window.myGauge = new Chart(ctx, config);
            };
    
            //document.getElementById('randomizeData').addEventListener('click', function () {
            //    config.data.datasets.forEach(function (dataset) {
            //        dataset.data = randomData();
            //        dataset.value = randomValue(dataset.data);
            //    });
    
            //    window.myGauge.update();
            //});
        </script>

    Code-behind:

    public class trafficSourceData
            {
    
                public string value { get; set; }
    
            }
    
            [WebMethod]
            public static string getTrafficSourceData()
            {
                
    
                string conn = ConfigurationManager.ConnectionStrings["aspnet-TestApplicationWithDatabase-20190820030542"].ConnectionString;
    
                using (SqlConnection cn = new SqlConnection(conn))
                {
                    string myQuery = "select * from traffic_data";
                    SqlCommand cmd = new SqlCommand();
                    cmd.CommandText = myQuery;
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = cn;
                    cn.Open();
                    List<trafficSourceData> t = new List<trafficSourceData>();
                    SqlDataReader dr = cmd.ExecuteReader();
                    if (dr.HasRows)
                    {
                        //int counter = 0;
                        while (dr.Read())
                        {
                            trafficSourceData tsData = new trafficSourceData();
                            tsData.value = dr["visit_count"].ToString();
                            //tsData.label = dr["traffic_source"].ToString();
                            //tsData.color = arrColor[counter];
                            t.Add(tsData);
                            //counter++;
                        }
                    }
                    return "{\"data\":" + JsonConvert.SerializeObject(t) + "}";
                }
                
            }

    Best regards,

    Yijing Sun

    Thursday, July 2, 2020 7:04 AM
  • User-1313071134 posted

    Thanks for your reply.

    I am using ASP.NET web application. I have a question

    What am I suppose to include here?

    $.each(JSON.parse(aData), function (inx, val) {
       .....
    });

    This is my configuration and this is how I connect to the SQL server

    protected void Page_Load(object sender, EventArgs e)
            {
    
                //Connect to the SQL server
                string myConnection = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;
                SqlConnection con = new SqlConnection(myConnection);
                String query = "SELECT* FROM DADLoggerTable";
                SqlCommand cmd = new SqlCommand(query, con);
                DataTable tb = new DataTable();
                try
                {
                    con.Open();
    
                    SqlDataReader dr = cmd.ExecuteReader();
                    tb.Load(dr, LoadOption.OverwriteChanges);
                    con.Close();
                }
                catch { }
                //Check if there is data in the datatable
                if (tb != null)
                {
                    //This is an example of how I included a chart
                    String chart = "";
                    chart = "<canvas id=\"line-chart\" width=\"120%\" height=\"30\"></canvas>";
                    chart += "<script>";
                    chart += "new Chart(document.getElementById(\"line-chart\"), { type: 'line', data: {labels: [";
    
    
                    //Select the first 460 data points
                    for (int i = 0; i < 460; i++)
                        chart += i.ToString() + ",";
                    chart = chart.Substring(0, chart.Length - 1);
    
                    chart += "],datasets: [{ data: [";
    
                    //Select data from the database and add to chart
                    String value = "";
                    for (int i = 0; i < tb.Rows.Count; i++)
                        value += tb.Rows[i]["Engine_Hours"].ToString() + ",";
                    value = value.Substring(0, value.Length - 1);
                    chart += value;
    
                    chart += "],label: \"Engine Hours\",borderColor: \"#cd3e3e\",fill: true}"; // Chart color
                    chart += "]},options: { title: { display: true,text: 'Engine Hours (hr)'} }"; // Chart title
                    chart += "});";
                    chart += "</script>";
    
                    //Render the chart
                    Literal1.Text = chart;
                   }
              }        
        }
    }

    This is how the circular gauge looks like.

    How to integrate your implementation in my current template. I tried to but I wasn't able to integrate them.

    Thank you

    Thursday, July 2, 2020 10:41 AM
  • User475983607 posted

    You need to learn JSON, JavaScript, chartjs, AJAX or fetch, and Web Web Methods.    Building a dynamic string is not a good approach.  You'll either build a JavaScript application that manages the chart or you'll build the chart using code blocks to populate the chart data on the server.

    Below are a few examples. 

    https://forums.asp.net/p/2129509/6169081.aspx

    https://forums.asp.net/t/2145924.aspx

    Example based on https://chart-js.com/documentation/charts/gauge-chart.php

    <%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="default.aspx.cs" Inherits="WebFormsDemo.chartjs._default" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
            <div class="col-md-12 py-2">
            <span class="badge badge-dark">Chart-JS.com</span>
        </div>
        <div class="col-md-6 offset-md-3 my-5">
            <div class="card">
                <div class="card-body">
                    <h1 class="pt-3 text-center">Chart JS Gauge Chart</h1>
                    <hr>
                </div>
                <div class="card-body">
                    <canvas id="myChart"></canvas>
                </div>
            </div>
        </div>
    
        <!-- https://chart-js.com/documentation/charts/gauge-chart.php -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
        <script>
        var ctx = document.getElementById('myChart').getContext('2d');
        var chart = new Chart(ctx, {
            // The type of chart we want to create
            type: 'doughnut',
    
            // The data for our dataset
            data: <%= Newtonsoft.Json.JsonConvert.SerializeObject(Model)%>,
    
            // Configuration options go here
            options: {
                circumference: 1 * Math.PI,
                rotation: 1 * Math.PI,
                cutoutPercentage: 90
            }
        });
        </script>
    </asp:Content>
    
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Helpers;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    namespace WebFormsDemo.chartjs
    {
       
        public partial class _default : System.Web.UI.Page
        {
            public ChartJsDataModel Model { get; set; }
            protected void Page_Load(object sender, EventArgs e)
            {
                Model = new ChartJsDataModel()
                {
                    labels = new string[] { "January", "February", "March", "April", "May" },
                    datasets = new Dataset[]
                     {
                         new Dataset()
                         {
                            backgroundColor = new string[] {"rgb(0, 99, 132)", "green", "red", "yellow", "orange" },
                            borderColor ="My First dataset",
                            label = "#fff",
                            data = new int[] { 5, 10, 5, 2, 20 }
                         }
                     }
                };
    
                var s = JsonConvert.SerializeObject(Model);
            }
        }
    
        public class ChartJsDataModel
        {
            public string[] labels { get; set; }
            public Dataset[] datasets { get; set; }
    
        }
    
        public class Dataset
        {
            public string label { get; set; }
            public string[] backgroundColor { get; set; }
            public string borderColor { get; set; }
    
            public int[] data { get; set; }
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, July 2, 2020 11:11 AM