C # Razor foreach loop syntax in Javascript
I got the following javascript code from google chart:
function drawTimeChart() {
var dataArray = generateTimeChartArray();
var data = google.visualization.arrayToDataTable([
['2001', '25'],
['2002', 35],
['2003', 25],
['2004', 55]
]);
var options = {
title: 'Reported devices in MAUDE based on the term since 1990',
backgroundColor: '#EFEEEF',
hAxis: { showTextEvery: 4 }
};
var chart = new google.visualization.LineChart(document.getElementById('MaudeTimeChart'));
chart.draw(data, options);
}
The data that I am inserting into the data I want to add dynamically. I've tried doing like this:
var data = google.visualization.arrayToDataTable([
@foreach (var item in Model.NumberOfReportedRecords){
[@Html.DisplayFor(modelItem => item.year), @Html.DisplayFor(modelItem => item.Status)]
}
]);
Does anyone know how to make this work?
+3
source to share
1 answer
You don't need to use Html.DisplayFor as it will render the template instead of just the value. Use simply @item.year
to get a value like this:
var data = google.visualization.arrayToDataTable([
@foreach (var item in Model.NumberOfReportedRecords){
['@item.year', '@item.Status']
}
]);
Refresh 1.
Also I have some doubts as to how you defined the foreach loop - it may not work, but you can also try something like this ( @:
clearly indicates the beginning of the content ):
@foreach (var item in Model.NumberOfReportedRecords)
{
@:['@(item.year)', '@(item.Status)'],
}
+6
source to share