3

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 insert into data i want to be dynamicly added. I 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)]
                 }
                ]);

Anyone know how to make this work?

1 Answer 1

6

You don't need to use Html.DisplayFor as it will render template instead of just value. Use simply @item.year for getting that value like:

var data = google.visualization.arrayToDataTable([
                @foreach (var item in Model.NumberOfReportedRecords){
                    ['@item.year', '@item.Status']
                 }
                ]);

Update 1.

Also I have some doubts about how you defined foreach loop - it might not work but you can also try something like that (@: explicitly indicates the start of content):

@foreach (var item in Model.NumberOfReportedRecords) 
        {
            @:['@(item.year)', '@(item.Status)'],
        }
Sign up to request clarification or add additional context in comments.

3 Comments

you should also look at HttpUtility.JavaScriptStringEncode to sanitize the output
Thanks! This is what i thought as well. But when i write this i get a bunch of errors saying "; expected", "Invalid expression term ,", "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement" Got any clue? While if i leave the foreach loop empty or insert the values manually like [2014, 15] no error is displayed
Than you very much! The last update fixed the problem! @: was the thing I was looking for :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.