[Chartjs]-Multiple Chart.js Charts in Partial Views Overwriting Each Other

2๐Ÿ‘

โœ…

I think the problem is that the barChartData gets overwritten by each of the partial views. Try putting that variable inside the document ready function.

Alternatively, use a self executing function to do all the chart stuff.

(function(){
    var data = {};
})();

Basically, the issue is that each of the partial views is adding a copy of barChartData to the page. Each of which is defined in the window scope. So the page is going to look something like this:

<script>
    var barChartData = {
        labels: ModelOneLabels,
        datasets: ModelOneData
    };
    ...
</script>

<script>
    var barChartData = {
        labels: ModelTwoLabels,
        datasets: ModelTwoData
    };
    ...
</script>

That will leave barChartData with the model two values.

You should be able to look at the generated page and see the multiple script tags. The console in your browsers developer tools should verify as well.

Here is how you can fix it:

<script>
    $(document).ready(function () {
        var barChartData = {
            labels: [@Html.Raw(Model.Labels)],
            datasets: [@Html.Raw(Model.Data)]
        };

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

        // I am not sure how you are using the window.myBar@name var
        // if you are referencing it later than you may need to adjust this part
        var myBar = new Chart(ctx, {
          type: 'bar',
          data: barChartData,
          options: {
              elements: {
                  rectangle: {
                      borderWidth: 2,
                      borderColor: 'rgb(0, 255, 0)',
                      borderSkipped: 'bottom'
                  }
              },
              legend: { 
                  position: 'bottom' 
              }, 
              title: {
                  display: true, 
                  text: '@Model.CurrentReport.Name'
              }
        })

});
</script>

Leave a comment