I was trying to customize google Column chart to add my own data from controller. I found easy solution but if someone knows better approach I am happy to modify my code.Assuming that we copy the code from https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart\[code\] <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 = http://stackoverflow.com/questions/12642204/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>\[/code\]So the first think I wanted to amend was to display Category name and number of orders. Solution was simple, I just removed Expensed so it looked like this:\[code\]['Category', 'Orders'], ['2004', 1000,], ['2005', 1170, ], ['2006', 660, ], ['2007', 1030, ]\[/code\]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:\[code\]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;\[/code\]In ViewI replaced data variable definition simply with my string that I built in controller
Html.Raw(Model.OrdersForGoogleChart)so final build looks like that:\[code\]<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 = http://stackoverflow.com/questions/12642204/@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>\[/code\]I found amazing that Razor in Asp.Net MVC speaks with js and js will digest string that was passed through razor without any issues.If you find a beter solution to I believe common problem let us know!
