[SOLVED] Is there a better way to create an 'n' number of charts in ChartJS and ASP.NET C#?

Issue

EDIT: I have narrowed it down to 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]);
            }

With the create chart making the chart id = to the array ‘labels’:

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

I am attempting to create a tool that creates an ‘n’ number of charts in ChartJS and save each of them as images. Currently, designButtonClick() sends the ‘event_fky’ value to
getDesigns(event_fky) in my controller. This method returns all designs with that foreign key. In turn, the chart plots each design on the chart. I need to evolve this into
something that can make a group individual charts for each design based on how many designs there are. My current solution, still conceptual, is to have methods in my controller
create chart variables ‘chartData [data here]’ and ‘labels[datahere]’ while looping through the designs returned from getDesigns, and sending those back to the JS script createChart
‘n’ number of times for each design. It would also send html chart/html element ids based on the design_name attribute to send back to createChart. This way, it is create a unique
chart ‘n’ number of times.

To save the charts as images, I would use the same set of element ids generated by getDesigns to send the charts to images using JS’ toBase64Image() function and saving them to the
user’s system.

Is this the best way of solving this problem? Or is this spaghetti, and is there a better method for this? My attempts to find better online answers have only resulted in docs on
updating one chart dynamically, not creating a dynamic number of charts. Much help is appreciated, code is below as well as a screenshot of the current chart output.

JavaScript:

   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

Solution

This is a working answer for the javascript:

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

            });
            return tmp;
        }();
        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 tmpi = null;
                $.ajax({
                    'async': false,
                    url: 'Tree/getDesigns',
                    type: 'POST',
                    data: {event_fky},
                    'success': function (data1) {
                        tmpi = data1;
                    }

                });
                console.log(event_fky);
                console.log(tmpi);
                return tmpi;
            }();
            var dLabels = [];
            var dLengths = [];
            for (var j = 0; j < designList.length; j++) {
                dLabels.push(designList[j].design_name);
                dLengths.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 (dLabels.length != 0) {
                createChart(dLabels, dLengths, event_name, event_length);
            }
        }
       
    }


  function createChart(labels, cData, evName, evLen) {
        // setup
        const data = {
            labels: labels,
            datasets: [{
                barThickness: 4,
                categoryPercentage: .5,
                label: evName,
                data: cData,
                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 config = {
            type: 'bar',
            data,
            options: {
                indexAxis: 'y',
                scales: {
                    y: {
                        beginAtZero: true
                    },
                    x: {
                        min: 0,
                        max: evLen,
                        ticks: {
                            stepSize: 100

                        }
                    }
                }
            }
        };

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

        return myChart;
    }

Answered By – Alden

Answer Checked By – Terry (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *