The goal is to get the data from the ViewBag.Array
to a Javascript array. The data is calculated in the controller so I cannot fetch it straight from the database. I need the data to draw a chart with jqplot. Code:
目标是将ViewBag.Array中的数据转换为Javascript数组。数据在控制器中计算,因此我无法直接从数据库中获取数据。我需要数据用jqplot绘制图表。码:
for(i = 0; i < @ViewBag.Array.Length; i++)
{
jScriptArray[i] = @ViewBag.Array[i];
}
The problem is "'i' does not exist in the current context" in the @ViewBag.Array[i]
but has no problems in the jScriptArray[i]
. Any help is appreciated.
问题是在@ ViewBag.Array [i]中“'我'在当前上下文中不存在”,但在jScriptArray [i]中没有问题。任何帮助表示赞赏。
3 个解决方案
#1
38
You may try the following:
您可以尝试以下方法:
var array = @Html.Raw(Json.Encode(@ViewBag.Array));
for(var i = 0; i < array.length; i++) {
jScriptArray[i] = array[i];
}
#2
0
<script>
var jScriptArray=[];
@{
for(i = 0; i < ViewBag.Array.Length; i++){
<text>jScriptArray[@i] = "@ViewBag.Array[@i]";</text>
i++;
}
}
</script>
You will end up with something like this in html file:
你将在html文件中得到类似的东西:
jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";
#3
-1
The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.
实现目标的最佳方法是创建一个JSON控制器,将数据返回到JSON数组中。
From your javascript you can request the data and then process it.
从您的JavaScript您可以请求数据,然后处理它。
Hope this helps
希望这可以帮助
#1
38
You may try the following:
您可以尝试以下方法:
var array = @Html.Raw(Json.Encode(@ViewBag.Array));
for(var i = 0; i < array.length; i++) {
jScriptArray[i] = array[i];
}
#2
0
<script>
var jScriptArray=[];
@{
for(i = 0; i < ViewBag.Array.Length; i++){
<text>jScriptArray[@i] = "@ViewBag.Array[@i]";</text>
i++;
}
}
</script>
You will end up with something like this in html file:
你将在html文件中得到类似的东西:
jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";
#3
-1
The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.
实现目标的最佳方法是创建一个JSON控制器,将数据返回到JSON数组中。
From your javascript you can request the data and then process it.
从您的JavaScript您可以请求数据,然后处理它。
Hope this helps
希望这可以帮助