2013-04-20 59 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序列化