实现此目的的另一种方法是使用 Google DataTable .Net Wrapper ( https://googledatatablelib.codeplex.com/ ),它可以使用强类型 System.DataTable,然后可以将其转换为 google.datatable 可视化JSON 格式。
此服务器端代码
public string GetStatisticsForChart(string messageCode)
{
//some repository that returns data....
var data = _statisticsRepository.GetPerMessage(messageCode);
//It simply returns a list of objects with Year and Count properties.
var query = (from t in data
group t by new {t.TimeStamp.Year}
into grp
select new
{
grp.Key.Year,
Count = grp.Count()
}).ToList();
//let's instantiate the DataTable.
var dt = new Google.DataTable.Net.Wrapper.DataTable();
dt.AddColumn(new Column(ColumnType.String, "Year", "Year"));
dt.AddColumn(new Column(ColumnType.Number, "Count", "Count"));
foreach (var item in query)
{
Row r = dt.NewRow();
r.AddCellRange(new Cell[]
{
new Cell(item.Year),
new Cell(item.Count)
});
dt.AddRow(r);
}
//Let's create a Json string as expected by the Google Charts API.
return dt.GetJson();
}
将生成以下 JSON 输出
{
"cols": [
{"type": "string", "id": "Year", "label": "Year"},
{"type": "number", "id": "Count", "label": "Count"}
],
"rows": [
{"c": [{"v": "2011"}, {"v": "1860"}]},
{"c": [{"v": "2012"}, {"v": "2000"}]}
]
}
这可以在 Asp.NET WebAPI 中使用,也可以直接在 ASP.NET MVC 控制器中使用。