How can I loop through an array with razor and javascript together ASP.net

Viewed 21

I am currently using ASP.NET MVC, I am using javascript to create a graph that represents data in my models. The Javascript is expecting the data in this format:

series: [{
        name: 'Bench',
        data: [
            10, 20, 30
        ]
    }],

However, I am trying to use razor to loop through my array in the data field as so:

series: [{
        name: 'Bench',
        data: [

            @for (int j = 0; j < numArry.Length; j++)
            {
                numArry[j] + ",";
            }
        ]
    }],

My issue is that the comma that separates my integers is not accepted by razor syntax. I need to comma to be repeated after every array integer otherwise the graph will only contain the last integer in the array.

series: [{
        name: 'Bench',
        data: [


            @numArry[0]
            ,
            @numArry[1]
            ,
            @numArry[2]
            ,
            @numArry[3]

        ]
    }],

This is my current solution that does work however, I can enter every element of the array manually.

1 Answers

Try it following ways..

  1. Create Model with same structure and serialize it to JSON

  2. Move the for loop outside of the series and declare a variable before the series code as below to get comma separated value.

@ {
var str = String.Join(",", numArry); 
}

series: [{ name: 'Bench', data: [ { @ {str } ] }],

Related