将参数从模型传递到javascript
Passing parameters from model to javascript
所以我在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()。
相关文章:
- 如何使用Javascript客户端对象模型检索Sharepoint 2010列表项权限
- 将JavaScript变量保存到Rails模型
- 如何创建具有默认值的JavaScript对象字段?(AngularJS模型相关)
- 将c#视图模型转换为javascript模型时转义HTML标记
- 将模型从Kendo Mvc UI网格传递到javascript函数
- 无法使用Javascript捕获引导模型
- 如何使用javascript访问sails.js模型中的属性
- 使用Javascript对象模型
- ASP.Net模型到Javascript-将数据从服务器传递到客户端
- 在我的php模型中用javascript更改一个html类
- 模型中的Javascript使用列表
- 从页面上的字段加载 JavaScript 模型
- 如何从 html 表数据填充 javascript 模型
- JavaScript 模型中的 MVC3 EditorFor() 更改值无法识别更改
- 在sharepoint javascript模型的每个循环中同步执行QueryAsync
- 使用组合的通用JavaScript模型
- 使用javascript模型表单
- 在服务器和客户端之间共享JavaScript模型代码,这种方法有效吗
- 如何在index.js文件中要求javascript模型文件
- 从javascript模型中获取对象列表