0

我将 ViewBag 中的 C# 2D 数组传递给我的 View,我想将其解析为 Javascript 2D 数组以将其用作谷歌图表的源。我努力了:

 var tab = @Html.Raw(@ViewData["tabComplet"]);
 var data = google.visualization.arrayToDataTable(tab);

但它不起作用,有人有想法吗?

4

1 回答 1

0

在GitHub 上查找整个项目或观看youtube 视频

在控制器中,添加以下代码

            // prepare a 2d array in c#
            ArrayList header = new ArrayList { "Task Name", "Hours"};
            ArrayList data1 = new ArrayList {"Work", 2};
            ArrayList data2 = new ArrayList { "Eat", 2 };
            ArrayList data3 = new ArrayList { "Sleep", 2 };
            ArrayList data = new ArrayList {header, data1, data2, data3};
            // convert it in json
            string dataStr = JsonConvert.SerializeObject(data, Formatting.None);
            // store it in viewdata/ viewbag
            ViewBag.Data = new HtmlString(dataStr);            

在 _Layout.cshtml 中,添加 Google 脚本

@*google chart*@
<script type="text/javascript" src="https://www.google.com/jsapi">   </script>

最后,在视图中添加以下代码

<script>    
    var data = JSON.parse('@ViewBag.Data');
    console.log(data);
</script>
<script type="text/javascript">
    google.load("visualization", "1", { packages: ["corechart"] });
    google.setOnLoadCallback(drawChart);
    function drawChart() {

        var chartData = google.visualization.arrayToDataTable(data);

        var options = {
            title: 'My Daily Activities'
        };

        var chart = new google.visualization.PieChart(document.getElementById('piechart'));

        chart.draw(chartData, options);
    }
</script>

<p>Use this area to provide additional information.</p>

i will show chart in there. but the data will come from viewdata instead of calling jQuery Ajax request.
<div id="piechart" style="width: 900px; height: 500px;"></div>
于 2015-09-20T07:11:29.810 回答