I'm trying to load a JavaScript array with an array from my model. Its seems to me that this should be possible.
Neither of the below ways work.
Cannot create a JavaScript loop and increment through Model Array with JavaScript variable
for(var j=0; j<255; j++)
{
jsArray = (@(Model.data[j])));
}
Cannot create a Razor loop, JavaScript is out of scope
@foreach(var d in Model.data)
{
jsArray = d;
}
I can get it to work with
var jsdata = @Html.Raw(Json.Encode(Model.data));
But I don't know why I should have to use JSON.
Also while at the moment I'm restricting this to 255 bytes. In the future it could run into many MBs.
JSON syntax is pretty much the JavaScript syntax for coding your object. Therefore, in terms of conciseness and speed, your own answer is the best bet.
I use this approach when populating dropdown lists in my KnockoutJS model. E.g.
...
Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.
This would be better approach as I have implemented :)
Hope this will help you to prevent you from iterating model ( happy coding )
I was working with a list of toasts (alert messages),
List<Alert>
from C# and needed it as JavaScript array for Toastr in a partial view (.cshtml
file). The JavaScript code below is what worked for me:I was integrating a slider and needed to get all the files in the folder and was having same situationof C# array to javascript array.This solution by @heymega worked perfectly except my javascript parser was annoyed on
var
use inforeach
loop. So i did a little work around avoiding the loop.And the javascript code is
Hope it helps
If it is a symmetrical (rectangular) array then Try pushing into a single dimension javascript array; use razor to determine the array structure; and then transform into a 2 dimensional array.
To expand on the top-voted answer, for reference, if the you want to add more complex items to the array:
@:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");
etc.
Furthermore, if you want to pass the array as a parameter to your controller, you can stringify it first:
myArray = JSON.stringify({ 'myArray': myArray });