将 ASP.NET C# 字典数据解析为 Google 可视化图表

本文关键字:Google 可视化 NET ASP 字典 数据 | 更新日期: 2023-09-27 18:32:47

我有一个以C#作为服务器语言的 ASP.net 应用程序。我这里有一个包含数据的字典,我想把它放在谷歌可视化图表中。我必须在运行时动态创建图表,因此没有硬编码的 HTML 标记。我有一个文档,我想打印到网站,但填写了我自己的数据:

 <script type="text/javascript">
     var data;
     var chart;
      // Load the Visualization API and the piechart package.
      google.charts.load('current', {'packages':['corechart']});
      // Set a callback to run when the Google Visualization API is loaded.
      google.charts.setOnLoadCallback(drawChart);
      // Callback that creates and populates a data table,
      // instantiates the pie chart, passes in the data and
      // draws it.
      function drawChart() {
        // Create our data table.
        data = new google.visualization.DataTable();
        data.addColumn('string', '');
        data.addColumn('number', 'Serie1'); // DATA HERE
        data.addColumn('number', 'Serie2'); // DATA HERE
        data.addRows([
          ['Mushrooms', 3,4], // DATA HERE
          ['Onions', 1,4],// DATA HERE
          ['Olives', 1,6],// DATA HERE
          ['Zucchini', 1,7],
          ['Pepperoni', 2,4]// DATA HERE
        ]);

        // Set chart options
        var options = {'title':'How Much Pizza I Ate Last Night',
                       'width':400,
                       'height':300};
        // Instantiate and draw our chart, passing in some options.
        chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        google.visualization.events.addListener(chart, 'select', selectHandler);
        chart.draw(data, options);
      }
      function selectHandler() {
        var selectedItem = chart.getSelection()[0];
        var value = data.getValue(selectedItem.row, 0);
        alert('The user selected ' + value);
      }
    </script>
    <!--Div that will hold the pie chart-->
    <div id="chart_div" style="width:400; height:300"></div>

那么如何格式化我的字典数据并替换虚拟数据???

将 ASP.NET C# 字典数据解析为 Google 可视化图表

您可以使用 Razor 将字典中的数据插入到脚本中:

<script type="text/javascript">
....
    data.addRows([
          @Model.DataRows
    ]);
....
</script>

定义您的模型:

public class ChartModel
{
    ....
    public string DataRows { get; set; }
    ....
}

并在视图顶部放置类似以下内容:@model [Your_Namespace].ChartModel .

然后在控制器中设置 DataRows 属性:

    public ActionResult Index()
    {
        Dictionary<string, int> datas = new Dictionary<string, int>();
        datas.Add("Januar 2015", 3129);
        datas.Add("Februar 2015", 3129);
        ChartModel model = new ChartModel();
        model.DataRows = string.Join(", " + Environment.NewLine, 
            datas.Select(d => "['" + d.Key + "', " + d.Value + "]"));
        return View(model);
    }