MVC: Iterating a Viewbag array in javascript
Asked Answered
J

4

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.

Jews answered 29/4, 2011 at 9:50 Comment(0)
E
59

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];
}
Experiment answered 29/4, 2011 at 9:56 Comment(4)
How about a two dimensional array? Using this technique it ends up one dimensional.Corrosive
@JohnMeyer did you figure out a way to work with two dimension viewbag array yet?Dynode
I think I ended up passing it to the view on the model instead of using the ViewBag.Corrosive
in my case it was Json.Serialize instead of Json.EncodeHairstreak
B
2
var [email protected](JsonConvert.SerializeObject(ViewBag.Array));

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

Bashkir answered 27/1, 2020 at 14:0 Comment(0)
M
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";
Morrow answered 2/2, 2015 at 18:59 Comment(0)
B
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

Bulter answered 29/4, 2011 at 9:57 Comment(3)
No, this can be done. No need to create a controller returning JSON for this.Experiment
Sorry for the can't be done, but it s better to use a JSON controller than using Viewbag for javascript server-side communication.Bulter
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.Experiment

© 2022 - 2024 — McMap. All rights reserved.