对于javascript和CSHTML不normaly工作 [英] For in javascript and cshtml not working normaly
问题描述
我正在asp.net MVC和我有一个奇怪的问题,我真的不明白......
在我CSHTML的开始,我已创建这样一个INT:
@
{
INT I = 0;
}
然后再在我的code,我用这个变量在JavaScript部分可以创建一个谷歌图与列的数量可变的,我做这种方式:
为(VAR J = 0; J< @ ViewBag.nbTechs; J ++)
{
data.addColumn('编号','@ ViewBag.techs [Ⅰ]');
@if(ⅰ!= 1000)
{
I = I + 1;
}
}
@ ViewBag.nbTechs等于9
@ ViewBag.techs是包含9字符串的字符串列表
块引用>这code创建我9列,但只能用在
@ ViewBag.techs
变量的第一个字符串名称的图表......我已签,如果varible
I
很好更新,是的,它是......所以,我真的不明白为什么这只是取名字...希望有人能帮助我,谢谢你提前
编辑:输出(列表中的第一个字符串)
解决方案
'@ ViewBag.techs [I]
是它在解析剃刀code其前服务器发送到视图,因此计算结果为'@ ViewBag.techs [0]
(查看源$ C $ C确认),所以你永远只能得到列表中的第一个值。删除你的
@ {INT I = 0; }
code,而是集合转换你JavaScript数组VAR techlist = @ Html.Raw(Json.En code(ViewBag.techs))
对于(VAR J = 0; J< @ ViewBag.nbTechs; J ++)
{
data.addColumn('编号',techlist [J]);
}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)
解决方案
'@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 arrayvar techlist = @Html.Raw(Json.Encode(ViewBag.techs)) for(var j = 0; j < @ViewBag.nbTechs; j++) { data.addColumn('number', techlist[j]); }
这篇关于对于javascript和CSHTML不normaly工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!