Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC: Iterating a Viewbag array in javascript

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.

like image 915
Esa Avatar asked Apr 29 '11 09:04

Esa


People also ask

Can we set ViewBag in JavaScript?

ViewBag is created on Server Side of the Web application and hence it is not possible to directly set it on Client Side using JavaScript or jQuery. Thus, only possible way is to set it by making an AJAX call to the Controller's Action method using jQuery AJAX function in ASP.Net MVC Razor.

Can we store array in ViewBag?

A simple Controller action which store the string array in the ViewBag and return to the view.

What is ViewBag in MVC with example?

The ViewBag in ASP.NET MVC is used to transfer temporary data (which is not included in the model) from the controller to the view. Internally, it is a dynamic type property of the ControllerBase class which is the base class of the Controller class.

Can we pass ViewBag from view to controller?

ViewBag can't pass data back to controller. You should post those values back inside the form. Easiest thing would be to not to use ViewBag and add the data to model type. If that's not possible, you can add the hidden inputs manually.


1 Answers

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];
}
like image 182
Darin Dimitrov Avatar answered Oct 14 '22 04:10

Darin Dimitrov