Linear Guage Chart in ASP.NET MVC forms fetching data from SQL Server using anychart.com charting library

34 Views Asked by At

Question

How can I create a covid linear gauge chart with LED and bar pointers to visualize progress in a C# ASP.NET web application using the AnyChart.com library, and how do I fetch the data from an SQL Server database? Following code I have tried with several variations but not able to display the chart.

Any Chart reference Library sample

https://www.anychart.com/products/anychart/gallery/Linear_Gauges/COVID-19_Vaccination_Rates.php

C# Code Chart.aspx.cs

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApp01
{
    public partial class Chart : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var jsonData = FetchDataFromDatabase();
                ScriptManager.RegisterStartupScript(this, GetType(), "DataScript", $"var gaugeData = {jsonData};", true);
            }
        }

        private string FetchDataFromDatabase()
        {
            var connectionString = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
            var query = "SELECT Region, CurrentValue, Maximum, ThresholdValue FROM tbl1 ";

            // Data structure to hold the fetched data
            var gaugeData = new List<object>();

            using (var connection = new SqlConnection(connectionString))
            {
                using (var command = new SqlCommand(query, connection))
                {
                    connection.Open();
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            gaugeData.Add(new
                            {
                                Region = reader["Region"].ToString(),
                                CurrentValue = Convert.ToDouble(reader["CurrentValue"]),
                                Maximum = Convert.ToDouble(reader["Maximum"]),
                                ThresholdValue = Convert.ToDouble(reader["ThresholdValue"])
                            });
                        }
                    }
                }
            }

            // Serialize the list to JSON
            var serializer = new JavaScriptSerializer(); // For .NET Core or later, use JsonSerializer.Serialize
            return serializer.Serialize(gaugeData);
        }
    }
}

ASP.NET Code Chart.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="Chart.aspx.cs" Inherits="WebApp01.Chart" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
      <script src="https://cdn.anychart.com/releases/v8/js/anychart-base.min.js"></script>
  <script src="https://cdn.anychart.com/releases/v8/js/anychart-ui.min.js"></script>
  <script src="https://cdn.anychart.com/releases/v8/js/anychart-exports.min.js"></script>
  <script src="https://cdn.anychart.com/releases/v8/js/anychart-linear-gauge.min.js"></script>
  <script src="https://cdn.anychart.com/releases/v8/js/anychart-table.min.js"></script>
  <link href="https://cdn.anychart.com/releases/v8/css/anychart-ui.min.css" type="text/css" rel="stylesheet">
  <link href="https://cdn.anychart.com/releases/v8/fonts/css/anychart-font.min.css" type="text/css" rel="stylesheet">
    <style>
           #container {
      width: 1000px;
      height: 800px;
      margin: 0;
      padding: 0;
    }
    </style>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
       <div id="container"></div>
      <script>
        anychart.onDocumentReady(function () {
            // Create and return simple linear gauge
            function drawGauge(value, settings) {
                // Create gauge with settings
                const gauge = anychart.gauges.linear();
                gauge.data([value, settings.value]);
                gauge.layout('horizontal');

                // Set scale for gauge
                const scale = anychart.scales.linear();
                scale.minimum(0).maximum(settings.maximum).ticks({ interval: 2 });

                // Set axis for gauge
                const axis = gauge.axis(0);
                axis.width('1%').offset('43%').scale(scale).orientation('bottom');

                // Create and set bar point
                const barSeries = gauge.bar(0);
                barSeries
                    .scale(scale)
                    .width('4%');

                // Create and set label with actual data
                const labelBar = barSeries.labels();
                labelBar
                    .enabled(true)
                    .offsetY('-15px');

                // Create and set LED point
                const ledPointer = gauge.led(1);
                ledPointer
                    .offset('10%')
                    .width('30%')
                    .count(settings.maximum)
                    .scale(scale)
                    .gap(0.55)
                    .dimmer(function () {
                        return '#eee';
                    });
                ledPointer.colorScale().colors(['#63b39b', '#63b39b']);

                return gauge;
            }

            const world = drawGauge(13.68, { maximum: value.Maximum, value: value.CurrentValue });

            const layoutTable = anychart.standalones.table();
            layoutTable
                .hAlign('right')
                .vAlign('middle')
                .fontSize(14)
                .cellBorder(null);


            layoutTable.contents([
                [null, 'COVID19 Vaccination - How far are we from the halfway mark?'],
                ['World', world],
            ]);


            layoutTable
                .getRow(0)
                .height(50)
                .fontSize(22)
                .hAlign('center');

            layoutTable.getCol(0).width(100);


            layoutTable.container('container');
            layoutTable.draw();
        });
      </script>
       
</asp:Content>
0

There are 0 best solutions below