0👍
✅
You could use @Html.Raw(Json.Serialize(Model))
in js to serialize your model and get all data. Then organize the data into the format you want.
1.Assume you have model:
public class ChartData
{
public int[] Data_Axis_X { get; set; }
public int[] Data_Axis_Y { get; set; }
}
2.Your action:
public IActionResult MyChart()
{
var model = new ChartData
{
Data_Axis_X = new int[] { 1997, 2003, 2005, 2009, 2014, 2018, 2019 },
Data_Axis_Y = new int[] { 1, 3, 5, 3, 1, 18, 9 }
};
return View(model);
}
3.MyChart.cshtml(Remember to add a reference to jquery in your project)
@model ChartData
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var model = @Html.Raw(Json.Serialize(Model));
var allData = [];
allData.push(['Year', 'Sales']);
$.each(model.data_Axis_X, function (index, item) {
var array = [];
array.push(item);
array.push(model.data_Axis_Y[index]);
allData.push(array);
console.log(Alldata);
});
var data = google.visualization.arrayToDataTable(allData);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
Results: