将参数从模型传递到javascript

Passing parameters from model to javascript

本文关键字:javascript 模型 参数      更新时间:2023-09-26

所以我在asp.net MVC4地理定位项目中工作,我在我的foreach循环中有一个问题,我的地图只是显示最后一个位置,这是我的视图代码:

@model  List<AgencyWebApplication.Models.HomeModel>
 @foreach(var ch in Model)
    {
    <script>
        var city = '@Html.Raw(ch.adress)';
        var attitude = '@Html.Raw(ch.attitude)';
        var longitude = '@Html.Raw(ch.longidue)';
        var indice = '@Html.Raw(ch.indice)';
        var array = [[city, attitude, longitude, indice]];
    </script>
    }
    <script src="@Url.Content("~/Scripts/Map.js")" type="text/javascript"></script>
    <input type="submit" name="Go" value="Go" onclick="getMap(array)" />
    <div id="map_canvas" style="width:600px; height:400px"></div>

和以下我的地图脚本代码:

function getMap(array) {
var myLatlng = new google.maps.LatLng(35.728329, -5.882750);
var mapOptions = {
    center: myLatlng,
    zoom: 17,
    mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
setMarkers(map, array);
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++)
{
    var place = locations[i];
    var myLatLng = new google.maps.LatLng(place[1], place[2]);
    var marker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        title: place[0],
        zIndex: place[3]
    });
}
return marker;
}

所以如果你有任何想法,我将非常感谢。

将您的模型序列化为视图模型属性,并在脚本中获取它,如

public class Geo{
 public string city{get;set;}
 public Decimal lat{get;set;}
 public Decimal lng {get;set;}
}

和视图模型

public class ViewModel{
 //other props
 public string GeoData{get;set;}
}

那样从数据库中填充它
 var ViewModel vm = new ViewModel();
 vm.GeoData = new JavaScriptSerializer.serialze(/*get the Geo data and pass it here*/);

现在在视图

<script>
 var geoData = $.parseJSON('@Html.Raw(Model.GeoData)');
 //here you can iterate the geo data and make use of it 
</script>

未测试的代码可能包含一些语法错误,也建议使用Json。Net序列化

您的foreach将每次重新分配变量"array",因此只有最后一个将在页面加载时存在。试着在浏览器中查看页面源代码,你就会明白我的意思了。

每次都需要将新值连接到数组中。可以在循环上方赋值数组,并在循环内部执行array.push()。