Pushing values to javascript array returning lots of errors

怎甘沉沦 提交于 2019-11-30 10:00:16

问题


I'm tring to fill a javascript array with lat longs that I can use to put markers on a map from my model but it's riddled with errors and I'm not sure why.

<div id="map"></div>
<script>

    var map,
    points = [];

    @foreach (var a in Model) {
        //Error: The name 'points' does not exist in the current context
                   //Error: ) expected ; expected (at front and end brackets)
        points.push({ lat: @a.Lat, lng: @a.Lon });
    }

    function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
            center: { lat: -34.397, lng: 150.644 },
            zoom: 8
        });
        //Error: The name 'points' does not exist in the current context
        @foreach (var p in points) {
            var marker = new google.maps.Marker({ position: p });
            //Error: The name 'marker' does not exist in the current context
            //Error: The name 'map' does not exist in the current context
            marker.setMap(map);
        }
    }

</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MyKey&callback=initMap"
    async defer></script>

Model

public class Vehicle
{
    [Key]
    public int ID { get; set; }
    public decimal Lon { get; set; }
    public decimal Lat { get; set; }
    public string VehType { get; set; }
    public string Driver { get; set; }
}

回答1:


@foreach() is razor code. It is evaluated on the server before its sent to the view. points is a client side javascript variable which does not exist at that point - its not in scope. Instead, you can assign your model to a javascript array using @Html.Raw(Json.Encode(Model). Your script would then be

var model = @Html.Raw(Json.Encode(Model)); // ignore the annoying 'syntax error'
points = [];
$.each(model, function (index, item) {
    points.push({ lat: item.Lat, lng: item.Lon})
})
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 8
    });
    for (var i = 0; i < points.length; i++) {
        var marker = new google.maps.Marker({ position: points[i] });
        marker.setMap(map);
    }
}



回答2:


Yes, because inside the @foreach loop, it's C# code, not Javascript. And your points is a Javascript variable, so you cannot just place it like that.

To fix this, you have 2 ways:

  1. Wrap it within <text> tag:

<text>points.push({ lat: @a.Lat, lng: @a.Lon });</text>

  1. In case your Javascript only has one line, you can use @: like this:

@:points.push({ lat: @a.Lat, lng: @a.Lon });



来源:https://stackoverflow.com/questions/33817069/pushing-values-to-javascript-array-returning-lots-of-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!