Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor MVC Populating Javascript array with Model Array

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.

like image 499
Tom Martin Avatar asked May 21 '14 10:05

Tom Martin


2 Answers

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>
like image 198
heymega Avatar answered Oct 22 '22 03:10

heymega


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:

var toasts = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(alerts));
toasts.forEach(function (entry) {
    var command = entry.AlertStyle;
    var message = entry.Message;
    if (command === "danger") { command = "error"; }
    toastr[command](message);
});
like image 13
Soma Mbadiwe Avatar answered Oct 22 '22 04:10

Soma Mbadiwe