Search code examples
javascript.netasp.net-mvcrazoricollection

How to iterate over @Model.ICollection in Java Script function?


I have a @Model.LoginCoordinates where LoginCoordinates is ICollection<Coordinates>.

The Coordinates class:

public class Coordinates {
    public int Id { get; set; }
    public double Latitude { get; set; }
    public double Longitude { get; set; }
}

Inside the view in I have:

<script>
    function f(){
       for (var i = 0, n  = @Model.LoginCoordinates.Count; i < n; i++) {
                    alert(i);//works fine, I just wanted to check if the loop works at all
       }
    }
</script>

It works fine, but instead of that I would like to display all the do:

 <script>
     function f(){
          for (var i = 0, n  = @Model.LoginCoordinates.Count; i < n; i++) {
                  var latitute = @Model.LoginCoordinates[i].Latitude;
                  var longituted = @Model.LoginCoordinates[i].Longitude;
         }
     }
</script>

But I cannot access i element of the LoginCoordinates because it is ICollection. Also I believe foreach is impossible at it is c# object.

Question: how to iterate over ICollection inside JavaScript?

EDIT

This above is SSCCE, the real code is;

  var map;
    function InitializeMap() {
        alert('works');
        var lat = @Model.LoginCoordinates.First().Latitude;
        var lon = @Model.LoginCoordinates.First().Longitude;
        var latlng = new google.maps.LatLng(lat, lon);
        var mapOptions =
        {
            zoom: 16,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            disableDefaultUI: true
        };
        map = new google.maps.Map(document.getElementById("map"), mapOptions); //this breaks the script

    }
    window.addEventListener('load', InitializeMap);

Solution

  • This should do it using JsonConvert from newtonsoft.json

    <script>
    var coordinatesJson='@Html.Raw(JsonConvert.Serialize(Model.LoginCoordinates.ToArray())'
    
    var coordinates=JSON.parse(coordinatesJson);
    
    //you now have coordinates as javascript  object
    
    var map;
    function InitializeMap() {
        // could loop over if needed
         for(var coords in coordinates) {
            // do something with coords
         }
    </script>