Experiencing difficulties integrating HighCharts for real-time data in an ASP.NET web form application

Below is the HighCharts JS code snippet that I have integrated into my aspx page:

Highcharts.chart('highcharts1', {
            chart: {
                type: 'bar'
            },
            title: {
                text: 'Number of MSMEs By District',
                align: 'left'
            },
            xAxis: {
                categories: JSON.parse(jsonDistrict),
                title: {
                    text: null
                },
                gridLineWidth: 1,
                lineWidth: 0
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Population (millions)',
                    align: 'high'
                },
                labels: {
                    overflow: 'justify'
                },
                gridLineWidth: 0
            },
            tooltip: {
                valueSuffix: ' millions'
            },
            plotOptions: {
                bar: {
                    borderRadius: '50%',
                    dataLabels: {
                        enabled: true
                    },
                    groupPadding: 0.1
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -40,
                y: 80,
                floating: true,
                borderWidth: 1,
                backgroundColor:
                    Highcharts.defaultOptions.legend.backgroundColor || '#FFFFFF',
                shadow: true
            },
            credits: {
                enabled: false
            },
            series: [{
                name: 'Year 1990',
                data: [631, 727, 3202, 721]
            }, {
                name: 'Year 2000',
                data: [814, 841, 3714, 726]
            }, {
                name: 'Year 2018',
                data: [1276, 1007, 4561, 746]
            }]
        });

I sourced this code from the official HighCharts website to display a static dataset in the chart. However, I am now working on making the chart dynamic by fetching district names and counts from a PLSQL database.

protected string BindDataToChart()
        {
            DataTable dt = objBO.Get_MSME_Chart_Data(new object[] { null });
            List<string> districtName = new List<string>();

            foreach(DataRow row in dt.Rows)
            {
                districtName.Add(row["DISTRICT_NAME"].ToString());
            }

            string jsonDistrict = JsonConvert.SerializeObject(districtName, Formatting.Indented);

            return jsonDistrict;
           
        }

I have been struggling to pass the dynamically generated district names from CS file to append to the JavaScript code's xAxis Categories section. Additionally, I plan to implement similar dynamic data for the series data in the chart.

I appreciate any assistance provided, thank you for your help.

Answer №1

Your code has a minor issue related to how you are utilizing jsonDistrict. By having your function BindDataToChart() return an array of strings, the data is already in the correct format. To incorporate it into your JavaScript, follow these steps:

let districtNames = <%= BindDataToChart() %>;

In your options section, make use of the following code:

categories: districtNames,

Answer №2

For your convenience, I have created a fully functional example. Here is the code snippet for the "Default.aspx" page:

<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebFormHighChart._Default" %>

    <!DOCTYPE html>

    <html lang="en">
    <head runat="server">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title><%: Page.Title %> - My ASP.NET Application</title>

        <script src="https://code.highcharts.com/highcharts.js"></script>
        <script src="https://code.highcharts.com/modules/series-label.js"></script>
        <script src="https://code.highcharts.com/modules/exporting.js"></script>
        <script src="https://code.highcharts.com/modules/export-data.js"></script>
        <script src="https://code.highcharts.com/modules/accessibility.js"></script>

        <style>
            .highcharts-figure,
            .highcharts-data-table table {
                min-width: 360px;
                max-width: 800px;
                margin: 1em auto;
            }
            
            // Additional styling rules here

        </style>
    </head>
    <body>
        <form runat="server"gt;

            <figure class="highcharts-figure">
                <div id="highcharts1"></div>

            </figure>

            <script type="text/javascript">
                // Highcharts configuration script goes here
            </script>


        </form>
    </body>
    </html>

Below is the corresponding code-behind file :

    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;

    namespace WebFormHighChart
    {
        public partial class _Default : Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {

            }

            protected string BindDataToChart()
            {
                string jsonDistrict = "['Africa', 'America', 'Asia', 'Europe']";
                return jsonDistrict;
            }

            public string JsonDistrict { get => BindDataToChart(); }
        }
    }

In this example, I utilized a property named "JsonDistrict" to populate the javascript chart setup. You can adapt this approach by defining a JS variable with data and integrating it into your scripts as required.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Safari browser is experiencing issues with the custom file upload script

My custom upload script allows users to easily select images for upload by clicking or dragging them into the designated box. A preview of the chosen image should appear, and this functionality works smoothly in Firefox and Chrome. However, I've encou ...

Google HTTP/REST OAuth: The authorisation code request contains a state parameter for the database user, while the access token request does not

I have successfully implemented the OAuth server flow for Google. The process begins with the user clicking a link that triggers javascript to open a popup containing a URI request, which is functioning perfectly: var endpoint = "https://accounts.google.c ...

Enhancing Angular template through iteration

I've been delving into an Angular project for a couple of weeks now, and I'm in the process of displaying data on the view. However, I've hit a roadblock as I attempt to work with iterations extracted from a large JSON file. Despite my best ...

Repetitive submissions of a form through Ajax post requests

Currently, I am utilizing this code to handle data sent via Ajax. Within the code, I am using the summernote editor. However, I have encountered an issue where if I submit the form while missing a required field, the form displays a 'required alert&ap ...

Adjust the dropdown selection when the page is reloaded from the server

On my webpage, I have 4 dropdown menus. When I choose an option from the first dropdown, an Ajax call filters the data for the other 3 dropdowns. After clicking the submit button, the second page is displayed. However, if I click the back button on the bro ...

Utilizing FlatList in React Native to display a parsed JSON array response

Can anyone help me with parsing the JSON response below into a FlatList? I'm not sure what I'm missing since it doesn't follow the standard key and value pair structure for rendering. {"list":["a","b","c","d"]} Here is my code... impo ...

Challenges with JavaScript calculations on dynamic HTML forms

Currently, I am immersed in a project focused on creating invoices. My progress so far involves a dynamic form where users can add and remove rows (as shown in the snippet below). I'm encountering an issue with my JavaScript and I could use some ass ...

Using Angular's $q service in the run block

I have a scenario where I need to load data from local files using the global loadJSON function (though it's not mandatory, it's recommended). Once the data is loaded from all the documents, I want to print the string 'i ve loaded'. T ...

What could be causing the jquery event not to be triggered?

I recently created the code example below: html: <input type="checkbox" name="terminal" class="all" data-terminal-id="9800" > javascript: function checkRightBarVisibility(){ if(this.checked){ alert('checked'); } } $(&ap ...

Dynamic cell loading in Vue using Vuetify's datatable functionality

<template> <v-data-table :headers="headers" :items="records" :items-per-page="5" show-select loading item-key="id" class="elevation-1" > <template v-slot:top> <div> <table-tabs> ...

Using AJAX and jQuery for database connectivity allows for seamless data retrieval and manipulation

Greetings! I am currently facing an issue with AJAX & JQUERY while trying to access my database. After researching online, I found a script that seemed promising for my problem. However, when I attempted to implement it, I encountered difficulties. Using ...

Modifications to aspx files will only be reflected after a rebuild

It was my understanding that I would be able to make changes to an aspx file in Visual Studio, refresh the browser, and see the updates without having to rebuild the entire solution. Unfortunately, this hasn't been the case for me... Any suggestions? ...

What could be causing the kendo autocomplete to display [object Object]?

I have encountered an issue when trying to update my kendo autocomplete using the code below. It displays [object Object] in the UI. <ng-template kendoGridCellTemplate let-dataItem="dataItem" let-rowIndex="rowIndex"> <kendo ...

Add a fresh category to a JSON document

Combining Express (Node.js) and Mongoose, I am developing a REST API and attempting to implement JWT token-based login. However, I have encountered an issue. Upon executing the code below: const mongoose = require('mongoose'); const User = mongo ...

The array's value was altered without any direct modification

In an attempt to prepend an element to a new array and return the modified array, I wrote the following code. Although it works, returning the original 'arr' instead of the modified 'newArr' results in changes to the 'arr'. f ...

Enhancing speed and efficiency through the utilization of Three.js

I'm currently working on my first Three.js / WebGL application, and while it runs smoothly on my PC (Chrome), I've noticed that the framerate tends to drop below 30 frames per second on other PCs. Despite the application not being overly complex ...

When using the combination of JBoss, RestEasy, and Jackson, you may encounter the error message: "Attempting to cast org.jboss.resteasy.core.ServerResponse to org.jboss.re

I am currently working on a REST Api using JBoss (AS 7.1), RestEasy, and Jackson. The web service returns an "Account" object, which is a simple POJO that was previously serialized in JSON without any issues. However, after making some changes to the code ...

Tips for Enhancing Generic Type field using JsonFormat

I have a standard form field class public class FormField<T> { private T value; private boolean disabled; // setters getters are here } T can either be LocalTime or LocalDate. I wish to configure Jackson Json to format the output based o ...

Accessing the content of a dynamically generated HTML Textbox in ASP.NET, which is one of multiple text boxes with unique IDs, in order to incorporate it into a href URL as a query string

Within my ASP.NET application, I have a static string that serves as the foundation for generating HTML content. This string contains placeholder values that are replaced dynamically at run time. The purpose of this static string is to construct multiple b ...

When incorporating a Textarea element within styled components in ReactJS, it causes the text to be inputted backwards due to the cursor

Currently, I am utilizing the Textarea component from react-textarea-autosize along with using styled from styled components. In a class, I have created a function called renderForm which is responsible for rendering a form containing a StyledTextarea. How ...