Integrating Google Charts in ASP.NET Core
January 31, 2020 by Anuraj
aspnetcore google-charts
This post is about integrating Google Charts in ASP.NET Core. We will learn about how to integrate Google Charts with Razor pages.
Google chart tools are powerful, simple to use, and free. Google Charts help to build interactive charts for browsers and mobile devices. You can get more details about Google Charts from https://developers.google.com/chart website.
To get started, create a web app project. And in the index.cshtml
file, remove the existing code add the following code.
So the above code is simple and straight forward. It will create a pie chart with the data and display it in the browser.
If you want convert the pie chart to bar chart, change the var chart = new google.visualization.PieChart(document.getElementById('chart'));
to var chart = new google.visualization.BarChart(document.getElementById('chart'));
it will become a bar chart.
Okay, but we are not using any C# code - how this is relevant in ASP.NET Core context. So in the above code we are creating a datatable
object in the JavaScript code. If we can convert C# data structures into this datatable
object, we will be able to display C# lists and data tables in Google Charts. There is code available in Google Charts website, where a PHP file used to serve data from JSON file.
So I converted that code to C# and which something like this.
And in the Razor pages code I wrote something like this.
And the above code is modified like this.
Now if you run the app, you will be able to see the chart data is coming from Razor page code. But this solution is not scalable and maintainable. So lets use a C# library which converts the List
and/or DataTable
objects from C# to JavaScript DataTable
, which is required for the Google Charts to render.
There is a Google DataTable .NET Wrapper
available in nuget - we need to install the package. We can do this by running the command dotnet add package Google.DataTable.Net.Wrapper --version 4.0.0
. Next lets modify the OnGetChartData
method and instead of creating the JSON with code use the library.
Now you will be able to use the server side data to generate a Google charts compatible datatable. Please note in the code instead of JsonResult I am retuning Content
.
You can use the same implementation in Web API and ASP.NET Core MVC - the change will be only in the client side consumer code. You can get more information about the .NET Wrapper in the GitHub page
Happy Programming :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub