Razor MVC Populating Javascript array with Model Array

Tom Martin picture Tom Martin · May 21, 2014 · Viewed 106.3k times · Source

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.

Answer

heymega picture heymega · May 21, 2014

This is possible, you just need to loop through the razor collection

<script type="text/javascript">

    var myArray = [];

    @foreach (var d in Model.data)
    {
        @:myArray.push("@d");
    }

    alert(myArray);

</script>

Hope this helps