What is the most efficient method for generating multiple charts using both ChartJS and ASP.NET C#?

UPDATE: After some refining, the code looks something like this:

for (i = 0; i < data.length; i++) {
          const newCanvas = document.createElement("canvas");
          newCanvas.id = data[i].design_name;
          const currentDiv = document.getElementById("chartSpace");
          var parentDiv = document.getElementById("gridHere");
           parentDiv.insertBefore(newCanvas, currentDiv);
           createChart([data[i].design_name], [data[i].design_start, data[i].design_end]);
            }

The chart created by `createChart` has an id equal to the elements in the 'labels' array:

 const myChart = new Chart(
            document.getElementById(labels),
            config
        );

I am working on a tool that generates 'n' number of charts using ChartJS and saves each one as an image. Currently, when `designButtonClick()` is called, the 'event_fky' value is sent to `getDesigns(event_fky)` in the controller. This method retrieves all designs related to that foreign key, and then plots each design on the chart. I need to enhance this functionality so that it can generate individual charts for each design based on the total number of designs available. My initial approach, though still in the concept phase, involves creating variables `'chartData[data here]'` and '`labels[datahere]`' in the controller while looping through the designs returned from `getDesigns`. These variables are then passed back to the JS script `createChart` 'n' times for each design. Additionally, HTML chart/html element ids based on the 'design_name' attribute are also generated and sent back to `createChart`. This way, a unique chart is created 'n' times.

To save the charts as images, I plan to use the same set of element ids generated by `getDesigns` to convert the charts into images using JavaScript's `toBase64Image()` function and saving them locally on the user's system.

Is this the most efficient way to tackle this problem? Or does it seem convoluted, suggesting there might be a better alternative? So far, my search for solutions online has only yielded documentation about updating a single chart dynamically, not about creating a dynamic number of charts. Any assistance or guidance would be greatly appreciated. The code snippet and a screenshot of the current chart output are provided below.

JavaScript Code:

   var labels = [];
   var cData = [];

   function designButtonClick() {
       var event_fky = 3;

       $.ajax({
           url: 'Tree/getDesigns',
           type: 'POST',
           data: { event_fky }
       }).done(function (data) {
           for (i = 0; i < data.length; i++) {
               labels.push(data[i].design_name);
               cData.push([data[i].design_start, data[i].design_end])
           }
         
           createChart(labels, cData);

       });
       
   }

   function createChart(labels, cData) {
       const data = {
           labels: labels,
           datasets: [{
               barThickness: 2,
               categoryPercentage: .5,
               label: 'Design Time',
               data: cData,
               backgroundColor: [
                   'rgba(255, 26, 104, 0.2)'
               ],
               borderColor: [
                   'rgba(255, 26, 104, 1)'
               ],
               borderWidth: 1,
               borderSkipped: false,
               borderRadius: 20
           }]
       };
       const config = {
           type: 'bar',
           data,
           options: {
               indexAxis: 'y',
               scales: {
                   y: {
                       beginAtZero: true
                   },
                   x: {
                       min: 0,
                       max: 6000,
                       ticks: {
                           stepSize: 1000
                       }
                   }
               }
           }
       };
       const myChart = new Chart(
           document.getElementById('myChart'),
           config
       );
   }

C# Controller:

public ActionResult getDesigns(int? event_fky)
        {

            var designs = from e in _context.designs
                         where (event_fky.HasValue ? e.event_fky == event_fky : e.event_fky == null)
                         select new
                         {
                             design_pky = e.design_pky,
                             design_name = e.design_name,
                             design_start = e.design_start,
                             design_end = e.design_end
                         };
            return this.Json(designs, JsonRequestBehavior.AllowGet);
        }

Designs Table:

--------Design--------
design_pky    |int
event_fky     |int
design_name   |varchar
design_start  |number
design_end    |number

Screenshot of Chart Output

Answer №1

Here is a solution for handling events and designs using JavaScript:

        var eventList = function () {
            var eventData = null;
            $.ajax({
                'async': false,
                url: 'Tree/getEventIDs',
                type: 'POST',
                data: {},
                'success': function (data) {
                    eventData = data;
                }

            });
            return eventData;
        }();
        for (var i = 0; i < eventList.length; i++) {

            event_fky = eventList[i].event_pky;
            event_name = eventList[i].event_name;
            event_length = eventList[i].event_end;


            var designList = function () {
                var designData = null;
                $.ajax({
                    'async': false,
                    url: 'Tree/getDesigns',
                    type: 'POST',
                    data: {event_fky},
                    'success': function (data1) {
                        designData = data1;
                    }

                });
                console.log(event_fky);
                console.log(designData);
                return designData;
            }();
            var designLabels = [];
            var designLengths = [];
            for (var j = 0; j < designList.length; j++) {
                designLabels.push(designList[j].design_name);
                designLengths.push([designList[j].design_start, designList[j].design_end]);
            }

            const newCanvas = document.createElement("canvas");

            newCanvas.id = event_name;

            const currentDiv = document.getElementById("chartSpace");
            var parentDiv = document.getElementById("gridHere");

            parentDiv.insertBefore(newCanvas, currentDiv);
            if (designLabels.length != 0) {
                createChart(designLabels, designLengths, event_name, event_length);
            }
        }
       
    }


  function createChart(labels, chartData, eventName, eventLength) {
        // setup
        const dataConfig = {
            labels: labels,
            datasets: [{
                barThickness: 4,
                categoryPercentage: .5,
                label: eventName,
                data: chartData,
                backgroundColor: [
                    'rgba(' + Math.random() * 85 + ', ' + Math.random() * 170 + ', ' + Math.random() * 255 + ', 1)'
                ],
                borderColor: [
                    'rgba(255, 26, 104, 1)'
                ],
                borderWidth: 0,
                borderSkipped: false,
                borderRadius: 20
            }]
        };

        // config
        const chartConfig = {
            type: 'bar',
            data: dataConfig,
            options: {
                indexAxis: 'y',
                scales: {
                    y: {
                        beginAtZero: true
                    },
                    x: {
                        min: 0,
                        max: eventLength,
                        ticks: {
                            stepSize: 100

                        }
                    }
                }
            }
        };

        // render init block
        const myChart = new Chart(
            document.getElementById(eventName),
            chartConfig
        );

        return myChart;
    }

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

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...

The current context does not contain a registration form

Hey everyone, I've been working on setting up a registration form based on an article I came across. I followed the provided steps and inserted the code as instructed, but I keep getting an error that reads "does not exist in current context." Am I mi ...

JavaScript Error: Unable to execute getJsonData due to function not found

I am encountering an issue with a function that retrieves JSON data from a URL Here is the code snippet: var retrieveJsonData = function(uri,callback){ $.ajax({ type: "GET", dataType: "jsonp", url: uri, jsonpCallback: 'r ...

Maximizing the efficiency of your .NET applications

My ASP.net application is built on .Net framework 4.0 and involves frequent database updates and grid refreshes, triggering various events to update tables. The issue I'm facing is that the application consumes a lot of RAM, easily exceeding 1GB withi ...

How to resolve undefined callback when passing it to a custom hook in React Native

I'm facing an issue with passing a callback to my custom hook: export default function useScreenshotDetection(onScreenshot) { useEffect(() => { ... onScreenshot(); ... }, []); } Strangely, the callback is not being detected ...

Utilizing JavaScript to implement an interactive :hover pseudo-class dynamic effect

After reviewing a question on adding a hover class to an element, I am now curious about how to do the opposite. I already have a main class for a button I am planning to create, where I will customize the background for each button using myButton.style.b ...

"Instead of seeing the expected content, a blank page is showing

I've been searching for a solution to this problem without any luck. Any assistance would be greatly appreciated. Initially, I created a "tabs" default project which worked fine as a base. However, after making a few modifications, the screen ended u ...

Use Angular.js to perform navigation after clicking the "Ok" button on a confirmation box

I encountered a problem with my requirement. I need a confirm box to appear when the user attempts to navigate to the next state/page. Only if the user clicks on the "Ok" button should it proceed to the next state; otherwise, it should stay as it is. Below ...

An error was encountered: Unable to assign value to the property "once" of [object Object] because it only has a

`Encountering an Uncaught TypeError: Cannot set property 'once' of [object Object] which has only a getter at HTMLDivElement.addEventListener (polyfills.js:1:146664). This issue is being faced during the process of upgrading the Angular version. ...

UserControl's Page_Load event not being triggered

After creating a C# class inside a class library and adding it to the default.aspx file, the page_load event is not firing. Here is the code snippet: What am I doing wrong? The page loads successfully but the label does not appear on the page. The contro ...

What is the method to retrieve response text?

This is the content of my register.js file: var formdata = new FormData(); formdata.append("name", name.value); formdata.append("username", username.value); formdata.append("email", email.value); formdata.append("password", password.value) ...

Issue with countdown timer when making modifications on my website utilizing Angular and TypeScript

I implemented a countdown timer in typescript on the homepage of my website. However, when I navigate to another page, I encounter a console error every second. .TS countDown() { var countDownDate = new Date("Jan 1, 2022 00:00:00").getTime ...

The maskededitextender in ajaxtoolkit is causing some issues and is not

I'm currently utilizing Visual Studio 2008 and following this tutorial: http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-maskededit-controls After running the web application, I encountered no errors, but it seems that the masking feature ...

What is the best way to eliminate a CSS style from a div?

I have implemented jQuery Autosize to automatically adjust the height of textarea elements. It works perfectly when I focus on the textarea element. However, when I blur out of the textarea, I want to reset the height to its default value. I am unsure of ...

Tips for fetching a particular item from a getItem dynamoDB in JavaScript

I am trying to retrieve an item from my AWS database. The item 'test2' is printing correctly in my console. However, I want to extract an attribute or variable from this item and store it as a variable named test. How can I accomplish this? For i ...

Wcf Service does not define Angular JS methods

I am utilizing a WCF Service within an AngularJS application. The WCF Service is functional, and I am attempting to display a list of user records from a SQL database. However, upon running the application, I encountered the following errors: angular.js: ...

The final output message from the NPM package is displayed right at the conclusion

Is there a way to add a log message at the end of the npm install process? To enable CLI tab autocompletion run: mypackage completion >> ~/.profile <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d5a5a7bab2a7b0a6 ...

After logging in, the ReturnUrl is consistently found to be null

I'm having trouble redirecting a user to the previous page after they login. The returnUrl parameter is always null for some reason. Below is the code I am using: Login method: public ActionResult Login(string returnUrl) { ViewBag.returnUrl = ...

Issues with Select2 Ajax functionality not functioning as intended

I am currently using the select2 library to create a dropdown menu with ajax functionality, but I am encountering some issues. Below is my code: $("#guests").select2({ multiple: true, minimumInputLength: 1, formatInputTooShort: fun ...

How to navigate through list items in React without triggering a re-render

Currently, I am in the process of learning React. Let's consider a scenario where I have a component called ListContainer that renders multiple ListItems. My goal is to keep track of which ListItem is currently selected, display it in a different colo ...