Razor MVC Populating Javascript array with Model Array
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);
});