MVC: Iterating a Viewbag array in javascript

2019-01-22 21:26发布

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:

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.

3条回答
Evening l夕情丶
2楼-- · 2019-01-22 21:48

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];
}
查看更多
倾城 Initia
3楼-- · 2019-01-22 21:50
<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:

jScriptArray[0] = "ArrayValue0";
jScriptArray[1] = "ArrayValue1";
jScriptArray[2] = "ArrayValue2";
查看更多
叛逆
4楼-- · 2019-01-22 21:50

The best way to achieve your goal is to create a JSON controller that returns the data into a JSON array.

From your javascript you can request the data and then process it.

Hope this helps

查看更多
登录 后发表回答