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.
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.
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 :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.