I wanted to use Chart.js charts in my ASP.NET Core projects and as there didn’t seem to be anything existing that fit the bill decided to do it myself.

Chart Creation

There seems to be a few projects around for generating the relevant javascript for Chart.js but all the ones I found either didn’t work in ASP.NET Core or didn’t work with version 2+ of Chart.js so I decided to create my own implementation. The Github project for this can be found here and the NuGet package here.

This is designed for use in an ASP.NET Core project, after installing the ChartJSCore package a chart object can be created in the Home controller (based on the default ASP.NET Core Web Application) Index method.


        public IActionResult Index()
        {
            Chart chart = new Chart();

            chart.Type = "line";

            Data data = new Data();
            data.Labels = new List<string>() { "January", "February", "March", "April", "May", "June", "July" };

            LineDataset dataset = new LineDataset()
            {
                Label = "My First dataset",
                Data = new List<double>() { 65, 59, 80, 81, 56, 55, 40 },
                Fill = false,
                LineTension = 0.1,
                BackgroundColor = "rgba(75, 192, 192, 0.4)",
                BorderColor = "rgba(75,192,192,1)",
                BorderCapStyle = "butt",
                BorderDash = new List<int> { },
                BorderDashOffset = 0.0,
                BorderJoinStyle = "miter",
                PointBorderColor = new List<string>() { "rgba(75,192,192,1)" },
                PointBackgroundColor = new List<string>() { "#fff" },
                PointBorderWidth = new List<int> { 1 },
                PointHoverRadius = new List<int> { 5 },
                PointHoverBackgroundColor = new List<string>() { "rgba(75,192,192,1)" },
                PointHoverBorderColor = new List<string>() { "rgba(220,220,220,1)" },
                PointHoverBorderWidth = new List<int> { 2 },
                PointRadius = new List<int> { 1 },
                PointHitRadius = new List<int> { 10 },
                SpanGaps = false
            };

            data.Datasets = new List<Dataset>();
            data.Datasets.Add(dataset);

            chart.Data = data;

            ViewData["chart"] = chart;

            return View();
        }

And then the Index view can be updated with the following code.


@{
    ViewData["Title"] = "Home Page";
}

<div><canvas id="lineChart"></canvas></div>

@{ChartJSCore.Models.Chart chart = (ChartJSCore.Models.Chart)ViewData["chart"]; }

@section Scripts {
    <script src="~/lib/Chart.js/dist/Chart.js"></script>
    <script>
        @Html.Raw(chart.CreateChartCode("lineChart"));
    </script>
}

Live Charts

It’s possible to make these charts (or indeed any Chart.js charts) update with live data at a regular interval by modifying the above Index view code to the following. An exampl of this can be seen here and the code is available here.


@{
    ViewData["Title"] = "Home Page";
}

<div><canvas id="lineChart"></canvas></div>

@{ChartJSCore.Models.Chart chart = (ChartJSCore.Models.Chart)ViewData["chart"]; }

@section Scripts {
    <script src="~/lib/Chart.js/dist/Chart.js"></script>
    <script>
        @Html.Raw(chart.CreateChartCode("lineChart"))

        setInterval(function () {
            // Get chart data
            $.get("Home/ChartData", function (data) {
                lineChart.data.datasets[0].data = data;
            })

            $.get("Home/ChartLabels", function (labels) {
                lineChart.data.labels = labels;
            })

            lineChart.update();
        }, 5000);
    </script>
}

The setInterval function loops every 5000 milliseconds and calls the methods ChartData and ChartLabels in the Home controller, these methods would ideally return live data (from a SQL database perhaps) but in the examples below just return fixed values.


        public int[] ChartData()
        {
            int[] data = { 59, 80, 81, 56, 55, 40, 72 };

            return data;
        }

        public List<string> ChartLabels()
        {
            List<string> lables = new List<string>() { "2", "3", "4", "5", "6", "7", "8" };

            return lables;
        }

5 Comments

Jake · 17th September 2018 at 6:50 pm

Hi, this is a great wrapper thank you. I am having a very hard time trying to figure out how to get SQL data into as chart data. I am not a dev by trade, but from time to time my role requires that I do a little. I have the stati values working great, but can you point me in the right direction please?

Thanks
Jake

    Shinigami · 18th September 2018 at 9:23 am

    Hi Jake, when getting data from from SQL I usually create a stored procedure, create an application specific SQL user and grant this user execute access on the stored procedure. I then use something like this https://blog.bitscry.com/2017/09/14/sql-stored-procedure-in-net-core/ to call the stored procedure from my application, you can then set the list returned as your data object.

    Hope that helps.

Michael · 14th November 2018 at 2:54 am

I think what Jake is asking is how to replace the static
Data = new List() { 65, 59, 80, 81, 56, 55, 40 },
with the values from a database. I have the values, I can’t figure out how to replace Data = new List() { 65, 59, 80, 81, 56, 55, 40 } with my own list.

Michael · 14th November 2018 at 3:08 am

The answer is to simply replace the label and data list with your own list
var bc = _repository.GetByCountry(2); //get the data here
var lstModel = new List();
List lst = new List();
List lstData = new List();

foreach (var v in bc)
{
lst.Add(v.CountryName);
lstData.Add(Convert.ToDouble(v.Total));
}

ChartJSCore.Models.Data data = new ChartJSCore.Models.Data();

data.Labels = lst;
LineDataset dataset = new LineDataset()
{
Label = “My data”,
//Data = new List() { 65, 59, 80, 81, 56, 55, 40 },
Data = lstData,

Leave a Reply

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