Razor-使用JavaScript在饼图中显示字典数据
本文关键字:显示 字典 数据 使用 JavaScript Razor- | 更新日期: 2023-09-27 17:59:24
我在模型中创建了一个字典,其中the City作为Key,the numbers of Kids作为Value(@model.dictionary)。
我希望你能帮助我,非常感谢。
<html>
<head>
</head>
<body>
<div id="piechart_3d" style="width: 900px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['City', 'Kids per Day'],
['LA', 100000],
['NY', 100000]
]);
var options = {
title: 'Kids per City',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}
</script>
</body>
</html>
您可以使用razor创建javascript数组,使用这个将List
转换为array的答案,您可以很容易地从Dictionary
转换:
var array = [@Html.Raw(String.Join(",", Model.dictionary.Select(x => "['" + x.Key + "', '" + x.Value +"']")))];
这将创建
[
['LA', 100000],
['NY', 100000]
]
你这样使用它,只需做一些修改。
function drawChart() {
var javaScriptArray = @Html.Raw(Json.Encode(Model.YourDotNetArray));
var data = google.visualization.arrayToDataTable([
['City', 'Kids per Day'],
@Html.Raw(String.Join(",", Model.dictionary.Select(x => "['" + x.Key + "', '" + x.Value +"']")))
]);
var options = {
title: 'Kids per City',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
chart.draw(data, options);
}