Razor MVC Populating Javascript array with Model Array

124,708

Solution 1

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>

Solution 2

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

Solution 3

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.

var desktopGrpViewModel = {
    availableComputeOfferings: ko.observableArray(@Html.Raw(JsonConvert.SerializeObject(ViewBag.ComputeOfferings))),
    desktopGrpComputeOfferingSelected: ko.observable(),
};
ko.applyBindings(desktopGrpViewModel);

...

<select name="ComputeOffering" class="form-control valid" id="ComputeOffering" data-val="true" 
data-bind="options: availableComputeOffering,
           optionsText: 'Name',
           optionsValue: 'Id',
           value: desktopGrpComputeOfferingSelect,
           optionsCaption: 'Choose...'">
</select>

Note that I'm using Json.NET NuGet package for serialization and the ViewBag to pass data.

Solution 4

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

Solution 5

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 in foreach loop. So i did a little work around avoiding the loop.

var allowedExtensions = new string[] { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };

var bannerImages = string.Join(",", Directory.GetFiles(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "Images", "banners"), "*.*", SearchOption.TopDirectoryOnly)
    .Where(d => allowedExtensions.Contains(Path.GetExtension(d).ToLower()))
    .Select(d => string.Format("'{0}'", Path.GetFileName(d)))
    .ToArray());

And the javascript code is

var imagesArray = new Array(@Html.Raw(bannerImages));

Hope it helps

Share:
124,708

Related videos on Youtube

Tom Martin
Author by

Tom Martin

Updated on January 28, 2022

Comments

  • Tom Martin
    Tom Martin over 2 years

    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.

    • Ehsan Sajjad
      Ehsan Sajjad almost 10 years
      you can access razor in js but not vice versa
  • Tom Martin
    Tom Martin almost 10 years
    Except I had to declare my array using the following notation var myArray= new Array();
  • heymega
    heymega almost 10 years
    Gald it works - Yes otherwise it will look for a C# object called myArray.
  • IAbstract
    IAbstract almost 9 years
    Big help. I thought I'd have some huge problems with building a javascript object from a model dictionary.
  • Bluesight
    Bluesight about 7 years
    Thank you! I neeeded this, because I had to pass a List of Strings to Javascript and then to Typescript for my Angular App :)
  • Asad
    Asad about 7 years
    There is an issue with your code. It should be @:myArray.push(ClassMember1: "@d.ClassMember1", ClassMember2: "@d.ClassMember2");
  • JhWebDev
    JhWebDev about 5 years
    @mmcrae, @d is declared inside the foreach loop. Notice the d has the term VAR in front. That enables it to be used inside the foreach loop
  • Allie
    Allie about 5 years
    note that this will render invalid javascript if the items in your array contain a quote or backslash. A way to fix that, is to use : @:myArray.push("@Html.Raw(HttpUtility.JavaScriptStringEncode‌​(d))");