【问题标题】:Passing parameters from model to javascript将参数从模型传递到 javascript
【发布时间】:2013-04-20 12:23:35
【问题描述】:

所以我在 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;
}

如果您有任何想法,我将不胜感激。

【问题讨论】:

    标签: javascript asp.net-mvc-3 google-maps razor google-api


    【解决方案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>
    

    未经测试的代码可能存在语法错误,推荐使用Json.Net进行序列化

    【讨论】:

      【解决方案2】:

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

      您每次都需要将新值连接到数组中。也许在循环上方分配数组并在循环内执行 array.push()。

      【讨论】:

      • 感谢 Tom,但问题是当在循环上方分配数组时,它给了我一个语法错误!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-13
      • 1970-01-01
      • 2013-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多