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.
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>
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);
});
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