2013-04-20 75 views
1

所以我工作在一个asp.net MVC4地理位置的项目,我有我的foreach循环的一个问题,我的地图只显示最后一个位置,这是我的看法 代码:从模型参数传递给JavaScript

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

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

回答

0

您的foreach将每次重新分配变量“数组”,因此只有最后一个在页面加载时存在。尝试在浏览器中查看页面源代码,您将看到我的意思。

您需要每次将新值连接到数组。也许分配循环上面的数组,并在循环内部做一个array.push()。

+0

感谢汤姆但问题是分配环以上的阵列时,它给我一个语法错误! – Mohammadov 2013-04-20 13:38:59

1

系列化你的模型视图模型性质,并得到它在脚本中像

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> 

代码不testeed可能包含一些语法errros,也被recomended使用Json.Net序列化