For in javascript and cshtml not working normaly

2019-09-04 12:20发布

I'm working on asp.net MVC and I have a weird problem that I really don't understand...

At the beginning of my cshtml, I have create a int like this :

@
{
int i = 0;
}

Then further in my code, I use this variable in a javascript section to create a google chart with a variable number of column and I do it this way :

for(var j=0; j<@ViewBag.nbTechs;j++)
{
    data.addColumn('number', '@ViewBag.techs[i]');
    @if (i != 1000)
    {
        i = i+1;
    }
}  
@ViewBag.nbTechs  is equal 9

@ViewBag.techs is a list of strings that contains 9 strings

This code creates me a charts with 9 column but only with the name of the first string in the @ViewBag.techs variable...

I have checked if the varible i is well updated and yes it is... So I really don't understand why it's only taking the first name ...

Hope someone can help me and thank you in advance

EDIT : output (first string in list)

enter image description here

1条回答
▲ chillily
2楼-- · 2019-09-04 12:45

'@ViewBag.techs[i]' is razor code which is parsed on the server before its sent to the view, so that evaluates to '@ViewBag.techs[0]' (view the source code to confirm) so you only ever get the first value in the list.

Remove your @{ int i = 0; } code, and instead convert you collection to a javascript array

var techlist = @Html.Raw(Json.Encode(ViewBag.techs))
for(var j = 0; j < @ViewBag.nbTechs; j++)
{
    data.addColumn('number', techlist[j]);
}  
查看更多
登录 后发表回答