Learn ASP.NET Core 3.1 : MVC, Razor Pages, Web API, Entity Framework Core, and Blazor.
Microsoft's official documentation can be found here. Looking for professional online training courses? Next weekend batches are starting in March 2020. More details here.

Use Google Charts in ASP.NET Core

At time your ASP.NET Core web applications want to display certain data in the form of bar chart or pie chart. Although there are plenty third-party components and libraries that you can use to accomplish this task, Google Charts is a simple yet feature rich client side option. To that end this article shows how Google Charts can be used to render simple bar charts and pie charts.

As an example we will display a simple pie chart followed by a bar chart as shown below:

The chart is quite straightforward. It displays number of hours spent on a project per day. The chart data is stored in a SQL Server table named WorkHours with the following schema:

And a sample set of values are shown below: 

Before you got to the ASP.NET Core and Google Charts specific code create this table and add the sample data.

Then begin by creating a new ASP.NET Core MVC web application. In order to fetch the chart data stored in the WorkHours table you need Entity Framework Core DbContext and entity classes. So, add NuGet package for Microsoft.EntityFrameworkCore.SqlServer.

The WorkHours entity class and the AppDbContext class is shown below:

[Table("WorkHours")]
public class WorkHours
{
    public int Id { get; set; }
    public string Day { get; set; }
    public int Hours { get; set; }
}
public class AppDbContext:DbContext
{
    public AppDbContext(DbContextOptions
    <AppDbContext> options) : base(options)
    {

    }
    public DbSet<WorkHours> WorkHours { get; set; }
}

Notice that the WorkHours class contains three properties - Id, Day, and Hours corresponding to the table columns.

Then open the HomeController and add an action named GetChartData() as shown below:

public IActionResult GetChartData()
{
    var data = db.WorkHours.ToList();
    return Json(data);
}

The GetChartData() action is called from the client side script. It simply grabs all the data from the WorkHours table and returns it to the caller in JSON format. The Json() method accepts a .NET type and returns its JSON representation.

We need jQuery Ajax to make server side calls, so add jQuery library to the wwwroot folder.

Next, open the Index.cshtml view file and add the following <script> references to it.

<script src="~/lib/jquery/dist/jquery.js"></script>
<script type="text/javascript" 
src="https://www.gstatic.com/charts/loader.js"></script>

The first <script> tag references the jQuery library whereas the second <script> tag references the Google Charts library.

Then add the following markup in the Index view:

<h1>Google Charts in ASP.NET Core</h1>
<button type="button" id="showchart">
Click here to render the chart
</button>
<br />
<div id="chart"></div>
<div id="msg"></div>

As you can see there is showchart button followed by two <div> elements. The <div> with id of chart is intended to render the bar or pie chart whereas the <div> with id of msg is intended to display error message if any.

Next, load what is known as Visualization API and the core chart package. This is done inside the ready() callback as shown below:

$(document).ready(function () {
    google.charts.load('current', 
    { 'packages': ['corechart'] });
});

When you click on the showchart button its click event handler is called. The click event handler basically fetches the chart data and formats it as expected by Google Charts. The jQuery code that fetches the data from the server is shown below:

var options = {};
options.url = '@Url.Action("GetChartData","Home")';
options.type = "GET";
options.dataType = "json";
options.success = function (data) {
};
options.error = function () {
    $("#msg").html("<h2>Error while 
using Google Charts!</h2>");
};
$.ajax(options);

Notice the code shown in bold letters.

The url property of the options JavaScript object is set to /Home/GetChartData using the Action() method. The dataType property is set to json indicating that GetChartData() action will return its data in JSON format. The success callback is discussed shortly. Then the code initiates the Ajax calls using $.ajax() method and by passing the options object to it.

The success callback is where chart data from the server is received and processed/ The code that goes inside the success callback is shown below:

options.success = function (data) {
    var chartData = [
        ['Day', 'Hours']
    ];
    $.each(data, function (i, item) {
        chartData.push([item.day, 
parseInt(item.hours)]);
    });
    var chartDataTable = google.visualization.
arrayToDataTable(chartData);
    var chartOptions = {
        title: "Hours spent per day",
        hAxis: {
            title: 'Hours',
            minValue: 0
        },
        vAxis: {
            title: 'Week Days'
        }
    };
    var chart = new google.visualization.PieChart
(document.getElementById('chart'));
    chart.draw(chartDataTable, chartOptions);
};

The above code first declares the chartData array. The first row of the chartData array is the vertical axis and horizontal axis labels - Day and Hours respectively. The code then iterates through the data received in the success callback (data parameter) and pushes an element consisting of vertical axis value and horizontal axis value respectively. Notice that day and hours are camel-case versions of the WorkHours class properties. Also notice that hours is explicitly converted into integer using parseInt() method.

The chartData array thus formed is then used to construct what is known as a DataTable. This is done using the arrayToDataTable() method.

Further, some chart options such as title of the chart, titles of the horizontal and vertical axis are assigned.

Finally, a PieChart is instantiated and drawn inside the chart <div> element based on the chartDataTable values. If you wish to draw a bar chart instead of a pie chart you would say:

var chart = new google.visualization.BarChart
(document.getElementById('chart'));

The following figure shows the bar chart version of the code in action.

You can read more about Google Charts here.

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant, trainer, author, yoga mentor, and meditation teacher. He has been programming, meditating, and teaching for 24+ years. He conducts instructor-led online training courses in ASP.NET family of technologies for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga to interested individuals. To know more about him click here.

Get article updates : Facebook  Twitter  LinkedIn

Posted On : 23 December 2019


Tags : ASP.NET ASP.NET Core MVC .NET Framework C# Visual Studio


Subscribe to our newsletter

Get monthly email updates about new articles, tutorials, code samples, and how-tos getting added to our knowledge base.

  

Receive Weekly Updates