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.
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.
A simple Controller action which store the string array in the ViewBag and return to the view.
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.
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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With