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.

4 Answers 4

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];
}
Sign up to request clarification or add additional context in comments.

4 Comments

How about a two dimensional array? Using this technique it ends up one dimensional.
@JohnMeyer did you figure out a way to work with two dimension viewbag array yet?
I think I ended up passing it to the view on the model instead of using the ViewBag.
in my case it was Json.Serialize instead of Json.Encode
3
var [email protected](JsonConvert.SerializeObject(ViewBag.Array));

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

Comments

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";

Comments

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

3 Comments

No, this can be done. No need to create a controller returning JSON for this.
Sorry for the can't be done, but it s better to use a JSON controller than using Viewbag for javascript server-side communication.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.