Find whole project on GitHub or watch the youtube video
In controller, add the following code
// 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);
In _Layout.cshtml, add the Google script
@*google chart*@
<script type="text/javascript" src="https://www.google.com/jsapi"> </script>
And at last, in the view add the below code
<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>
ViewBagandViewDataare not the same thing