Chartjs-How to connect a charts.js chart to data

1👍

Here is a whole working demo:

Model:

public class ChartJs
{
    public string type { get; set; }
    public bool responsive { get; set; }
    public Data data { get; set; }
    public Options options { get; set; }
}

public class Data
{
    public string[] labels { get; set; }
    public Dataset[] datasets { get; set; }
}

public class Dataset
{
    public string label { get; set; }
    public int[] data { get; set; } 
    public string[] backgroundColor { get; set; }
    public string[] borderColor { get; set; }
    public int borderWidth { get; set; }
}

public class Options
{
    public Scales scales { get; set; }
}

public class Scales
{
    public Yax[] yAxes { get; set; }
}

public class Yax
{
    public Ticks ticks { get; set; }
}

public class Ticks
{
    public bool beginAtZero { get; set; }
}

Index.cshtml:

@page
@model IndexModel
<h1>testReport2</h1>


<div class="chart-container" width="600" height="400">
    <canvas id="myChart"></canvas>
</div>
          
@section Scripts
{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js" integrity="sha256-qSIshlknROr4J8GMHRlW3fGKrPki733tLq+qeMCR05Q=" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.css" integrity="sha256-IvM9nJf/b5l2RoebiFno92E5ONttVyaEEsdemDC6iQA=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js" integrity="sha256-arMsf+3JJK2LoTGqxfnuJPFTU4hAK57MtIPdFpiHXOU=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script>
    <script>
     document.addEventListener('DOMContentLoaded', (event) => {

    var ctx = document.getElementById('myChart');
    var myChart = new Chart(ctx, @Html.Raw(Model.ChartJson) );

  });
    </script>
}

Index.cshtml.cs:

public class IndexModel : PageModel
{
    private readonly RazorProj3_1Context _context;
    public IndexModel(RazorProj3_1Context context)
    {
        _context = context;
    }
    public ChartJs Chart { get; set; }
    public string ChartJson { get; set; }
    public List<int> GetJson()
    {
        //get the data you want from database...

        var data = _context.Test.Select(a => a.Index).ToList();
        return data;
    }

    public void OnGet()
    {
        // be sure replace `data: [12, 19, 3, 5, 2, 3]` to `data:[]`
        var chartData = @"{type: 'bar',responsive: true,data:{
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [],
                backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
                'rgba(75, 192, 192, 0.2)',
                'rgba(153, 102, 255, 0.2)',
                'rgba(255, 159, 64, 0.2)'
                    ],
                borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
                'rgba(75, 192, 192, 1)',
                'rgba(153, 102, 255, 1)',
                'rgba(255, 159, 64, 1)'
                    ],
                borderWidth: 1
            }]
        },
        options:
        {
            scales:
            {
                yAxes: [{
                    ticks:
                    {
                        beginAtZero: true
                    }
                }]
            }
        }
    }";

        Chart = JsonConvert.DeserializeObject<ChartJs>(chartData);

        var res = GetJson();  //get the data
        
        //must remember to initialize the array....
        Chart.data.datasets[0].data =new int[res.Count()];
        for (int i = 0; i < res.Count(); i++)
        {
            Chart.data.datasets[0].data[i] = res[i];
        }
        ChartJson = JsonConvert.SerializeObject(Chart, new JsonSerializerSettings
        {
            NullValueHandling = NullValueHandling.Ignore,
        });
    }

}

Result:

enter image description here

Leave a comment