【发布时间】:2016-12-17 12:06:06
【问题描述】:
我正在使用 google api 来显示地图。在我的控制器中,我编写了以下 c# 代码:
var sedi = new List<string>();
sedi.Add("Via Gavinana, 19, Roma");
sedi.Add("Val de Seine, 94600 Choisy le Roi");
sedi.Add("Street 21,Shuwaikh, Kuwait");
ViewBag.sediList = sedi;
return View(ViewBag.sediList);
在我看来:
@{
var vb = (List<string>)ViewBag.sediList;
}
function GetLatLon (address, callback) {
console.log(address);
var location = new Array();
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
callback(location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function addMarker (location, map) {
var marker = new google.maps.Marker({
position: location,
map: map
});
}
function initMap() {
GetLatLon("@vb", function(location) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: location
});
for (var i = 0; i < 3; i++) {
addMarker(location, map);
}
});
}
我想在地图上显示三个标记,对应于列表中写入的位置vb
但是地址有System.Collections.Generic.List1[System.String] 值而不是地址的实际值。
如何将列表作为参数传递给 Javascript 中的 GetLatLon 函数?我该如何解决?
编辑
我需要在地图上显示三个标记,foreach 地址。 我写:
function GetLatLonByAddress (address) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == 'OK') {
location = { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() };
return location;
console.log (location);
}
return;
});
}
function initMap() {
GetLatLon('@(new Microsoft.AspNetCore.Html.HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)))', function(location) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: location
});
for (var i = 0; i < 3; i++) {
addMarker('@(new Microsoft.AspNetCore.Html.HtmlString(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Maps)))', map, i);
}
});
}
function addMarker (location, map, count) {
var locationArr = JSON.parse(location);
var marker = new google.maps.Marker({
position: GetLatLonByAddress(locationArr[count]),
map: map
});
}
有可能是这样的吗?我该如何解决?
【问题讨论】:
-
返回视图(ViewBag.sediList); - 看起来有点奇怪。如果您使用 ViewBag 并且 View 上没有模型 - 您需要返回 View()。如果有一个模型,包含 sediList - 那么你不需要 ViewBag。只需通过模型传递数据
-
GetLatLon("@vb", function(location) - 这里传递的是字符串,而不是数组
-
您需要将其分配给 javascript 变量 -
var vn = '@Html.Raw(Json.Encode(ViewBag.sediList))';,这将是您的 3 个地址字符串的数组。但是将代码更改为删除ViewBag.sediList = sedi;并使用return View(sedi);并在视图中添加@model List<string>然后使用'@Html.Raw(Json.Encode(Model))'; -
@FabioBit System.Web.Mvc
-
@FabioBit,mvc核心请参考this answer
标签: javascript c# arrays list asp.net-core-mvc