Assuming that we copy the code from https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart
<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([
['Year', 'Sales', 'Expenses'],
['2004', 1000,
400],
['2005', 1170,
460],
['2006', 660,
1120],
['2007', 1030,
540]
]);
var options = {
title: 'Company
Performance',
hAxis: {title:
'Year', titleTextStyle:
{color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"
style="width:50%;float:left"></div>
['Category', 'Orders'], ['2004', 1000,], ['2005', 1170, ], ['2006', 660, ], ['2007', 1030, ]But those are hard coded data and I wanted to have my own category names and name of orders from my Data base.
I created in controller custom string and then pass it to script.
Controller:
foreach (var d in
model.DinerCategoryOrders) // Build string for google chart js
{
// ['Pre-School', 1000], Template
GoogleOrdersCount += "['" +
d.CategoryName + "', " + d.OrdersCount + "],";
}
model.OrdersForGoogleChart = "google.visualization.arrayToDataTable([['Category',
'Orders']," + GoogleOrdersCount +"
]);";
return model;
I replaced data variable definition simply with my string that I built in controller:
@Html.Raw(Model.OrdersForGoogleChart)
so final build looks like that:
<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 = @Html.Raw(Model.OrdersForGoogleChart)
var options = {
title: 'Company
Performance',
hAxis: {title: 'Year', titleTextStyle:
{color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
If you find a beter solution to I believe common problem let me know!
You can also follow this tutorial on
http://stackoverflow.com/questions/12642204/customizing-google-columnchart-in-asp-net-mvc
Comments
Post a Comment