18

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.

Jacques Snyman
  • 4,115
  • 1
  • 29
  • 49
Esa
  • 1,636
  • 3
  • 19
  • 23

4 Answers4

57

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];
}
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2
var array=@Html.Raw(JsonConvert.SerializeObject(ViewBag.Array));

you can make use of JsonConvert.SerializeObject Hope this Helps.

LeArm
  • 21
  • 2
1
<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";
Dmitry Bosikov
  • 751
  • 6
  • 5
0

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

alexl
  • 6,841
  • 3
  • 24
  • 29
  • No, this [can be done](http://stackoverflow.com/questions/5830549/mvc-iterating-a-viewbag-array-in-javascript/5830594#5830594). No need to create a controller returning JSON for this. – Darin Dimitrov Apr 29 '11 at 09:58
  • Sorry for the can't be done, but it s better to use a JSON controller than using Viewbag for javascript server-side communication. – alexl Apr 29 '11 at 10:00
  • 1
    for `javascript -> server` communication yes, it's better, I agree. But here we are talking about `server -> javascript` communication. The server already sent a view model to the view, it would be bad to perform an additional AJAX request just to JSON serialize this model when this can be done directly. – Darin Dimitrov Apr 29 '11 at 10:05