

Google charts with DataTable .NET Wrapper and API data in ASP.NET 6.0 Razor Page...
source link: https://blog.medhat.ca/2022/01/google-charts-with-datatable-net.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Google charts with DataTable .NET Wrapper and API data in ASP.NET 6.0 Razor Pages App
You have data from an API (or any other data source like a database) and wish to display the results in a chart. The library we will use for generating charts is the freely available Google Charts JavaScript-based API. The Google DataTable .NET Wrapper is used to create a lightweight representation of the google.visualization.DataTable object directly in Microsoft.NET. The wrapper allows for the creation of the appropriate JSON which is easily ingested by the Google Chart Tools JavaScript library.
I will show you how to generate six types of charts to display dynamically generated data. The source of data will be an API at https://northwind.vercel.app/api/orders that displays orders. I will work with the ASP.NET Razor Pages template (AKA Web App).
Source code:
The environment I am using is: https://github.com/medhatelmasry/OrdersChartRazorGoogleWrapper
- .NET version 6.0.100
- Visual Studio Code
The products API
Project setup
dotnet new razor -f net6.0 -o OrdersChartRazorGoogleWrapper
Change directory into the new folder and open the project inside VS Code with the following commands:
cd OrdersChartRazorGoogleWrapper
code .
dotnet add package Google.DataTable.Net.Wrapper
Address & Order model classes
public class Address {[JsonPropertyName("street")]public string? Street { get; set; }[JsonPropertyName("city")]public string? City { get; set; }[JsonPropertyName("region")]public string? Region { get; set; }[JsonPropertyName("country")]public string? Country { get; set; }
public class Order {[JsonPropertyName("id")]public int Id { get; set; }[JsonPropertyName("customerId")]public string? CustomerId { get; set; }[JsonPropertyName("employeeId")]public int? EmployeeId { get; set; }[JsonPropertyName("shipVia")]public int? ShipVia { get; set; }[JsonPropertyName("freight")]public decimal? Freight { get; set; }[JsonPropertyName("shipName")]public string? ShipName { get; set; }[JsonPropertyName("shipAddress")]public Address ShipAddress { get; set; } = null!;
Reading data
@page@model ChartDataModel
using System.Text.Json;using Google.DataTable.Net.Wrapper;using Microsoft.AspNetCore.Mvc;using Microsoft.AspNetCore.Mvc.RazorPages;using OrdersChartRazorGoogleWrapper.Models;namespace OrdersChartRazorGoogleWrapper.Pages;public class ChartDataModel : PageModel {private readonly ILogger<ChartDataModel> _logger;public ChartDataModel(ILogger<ChartDataModel> logger) {_logger = logger;public async Task<IActionResult> OnGet() {Order[] orders = await GetOrdersAsync();var data = orders.GroupBy(_ => _.ShipAddress.City).Select(g => newName = g.Key,Count = g.Count().OrderByDescending(cp => cp.Count).ToList();//let's instantiate the DataTable.var dt = new Google.DataTable.Net.Wrapper.DataTable();dt.AddColumn(new Column(ColumnType.String, "Name", "Name"));dt.AddColumn(new Column(ColumnType.Number, "Count", "Count"));foreach (var item in data) {Row r = dt.NewRow();r.AddCellRange(new Cell[] {new Cell(item.Name),new Cell(item.Count)dt.AddRow(r);//Let's create a Json string as expected by the Google Charts API.return Content(dt.GetJson());private async Task<Order[]> GetOrdersAsync() {HttpClient client = new HttpClient();var stream = client.GetStreamAsync("https://northwind.vercel.app/api/orders");var products = await JsonSerializer.DeserializeAsync<Order[]>(await stream);return products!;
At this stage, let's run our web application and verify that we are indeed able to read data from the Orders API and subsequently generate JSON data. Run your application with:
dotnet watch run
Point your browser to https://localhost:7205/chartdata
NOTE: you will need to adjust the port number to suit your environment.
This is what was revealed in my browser:
We have a sense of assurance that our data is ready to be displayed in a chart.Charting the data
Replace your Pages/Index.cshtml with the following code:
If you point your browser to the home page, you should see six charts, namely: column, line, pie, area, bar and pie 3D charts.
Conclusion
It is very easy and inexpensive (free) to use Google Charts to generate charts in an ASP.NET Razor application. The .NET Google DataTable wrapper (Google.DataTable.Net.Wrapper) makes it even easier.
Recommend
-
61
VueDatatable - Bulma themed, VueJS powered Datatable with server-side loading and JSON template setup
-
38
平时写代码的时候经常会遇到DataTable与List<T>之间的转换操作,由于DataTable数据集合不像List<T>指定了对应的T类型,所以在操作的时候没有List<T>方便,为了方便两个集合的转换,特此写下以下类记录两者之间的互换。classModelConvertHelper&l...
-
29
“There were 5 Exabytes of information created between the dawn of civilization through 2003, but that much information is now created every 2 days”:Eric Schmidt If you a...
-
47
虽然pandas是数据分析、机器学习等必备利器,但现在流行的机器学习应用训练模型动辄需要GB级别的数据,很多时候pandas无法快速读取大数据文件或者进行高效运算,甚至可能存在内存溢出等情况。 如果是R语言的用户应该很熟悉data.t...
-
37
README.md
-
48
jQuery Datatables For Laravel 5.x A simple package to ease datatable.js server side operations This package is created to handle server-side...
-
31
Angular Datatable to Export data into Excel, CSV, PDF, Print and Copy I have already shared angular datatable...
-
6
Presenting Data with the Webix DataTableJune 19th 2021 new story5
-
49
Using Google Charts API with an ASP.NET Core 6.0 Razor Pages App Google Charts is a free JavaScript API that you can use to generate good looking charts on a web page. Although it has nothing to do with C# and .NET, we can still...
-
8
Generate charts with Google DataTable .NET Wrapper from ASP.NET 6.0 Razor Pages App The scenario that this article addresses is a situation whereby there is server-side generated data that needs to be displayed on a web page as a...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK