简体   繁体   中英

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

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.

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 } ] }],

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM