Chartjs-Chart.js generate chart with foreach mvc

0👍

You are duplicating the id here. The code statement

<tbody>
    <tr>
        @foreach(var hash in model)
        {
        <td>
            <div height="50" width="80">
                <canvas id="tableChart" data-hash="@hash.Count" height="50" width="80"></canvas>
            </div>
        </td>
        }
    </tr>
</tbody>

actually create the multiple canvas elements with same id which is an anti pattern.

Also when you execute:

var ctx = document.getElementById('tableChart').getContext('2d');

it returns only one element.

Better will be to add dynamic class to each canvas element and create the chart looping again.

Something like following:

<table class="table">
<thead>
    <tr>
        <th>Chart</th>         
    </tr>
</thead>
<tbody>
    <tr>
        @foreach(var hash in model)
        {
        <td>
            <div height="50" width="80">
                <canvas class="tableChart@hash" data-hash="@hash.Count" height="50" width="80"></canvas>
            </div>
        </td>
        }
    </tr>
</tbody>

and then you can use getElementsByClassName to get all the elements and draw chart within those.

Pardon me if there is any bad syntax.

0👍

Try this. It will loop over each canvas element by class name and generate the chart.

<table class="table">
    <thead>
        <tr>
            <th>Chart</th>         
        </tr>
    </thead>
    <tbody>
        <tr>
            @foreach(var hash in model)
            {
            <td>
                <div height="50" width="80">
                    //note the change of `id` to `class`
                    <canvas class="tableChart" data-hash="@hash.Count" height="50" width="80"></canvas>
                </div>
            </td>
            }
        </tr>
    </tbody>
</table>



 <script>
   $(".tableChart").each(function(i) {
       var hashCount = $(this).attr("data-hash");
       var ctx = $(this).getContext('2d');

       var myChart = new Chart(ctx, {
           type: 'line',
           data: {
               labels: ["A","B","C","D"],
               datasets: [{
                   data: [1,2,3, hashCount],
                   backgroundColor: ["red", "gray","blue","green"],
                   borderColor: "rgb(27,163,198)",
                   fill: false,
                   lineTension: 0.3,
                   radius: 1,
                   borderWidth: 1,
               }],
           },
           options: {      
           ...
           },
        });
   });
</script>

Leave a comment