【发布时间】:2015-10-12 19:09:21
【问题描述】:
我正在尝试将所有事件返回到 Google 地图,但由于某种原因没有返回任何内容,我也在使用 ajax: 这是控制器:
public ActionResult LocateEvent()
{
DataModel1 db = new DataModel1();
ViewBag.Title = "Locate Event";
return View(db.Events.ToList());
}
[HttpPost]
public ActionResult Search(string Location)
{
DataModel1 GE = new DataModel1();
var result = GE.Events.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
这是我尝试使用 ajax 使用 lat 和 long 显示所有事件的视图:
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
@*<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false"></script>*@
<script src="http://maps.google.com/maps/api/js?sensor=true" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var gmarkers = [];
var map;
function initialize() {
var mapProp = {
center: new google.maps.LatLng(-33.875233, 25.4443775), //P.E Lat and Lon
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
for (i = 0; i < gmarkers.length; i++) {
gmarkers[i].setMap(null);
}
$.ajax({
type: "POST",
url: '@Url.Action("Search", "Events")', //"../Map/Search"
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ "Location": x }),
dataType: "json",
success: function (data) {
var table = "<table class='table'>";
$.each(data, function (index, value) {
table += "<tr><td>" + value.EventName + "</td></tr>";
var latlng = new google.maps.LatLng(value.EventLat, value.EventLong);
var marker = new google.maps.Marker({
position: latlng,
icon: "../pinkball.png",
map: map
});
gmarkers.push(marker);
});
table += "</table>";
$("#myData").html(table);
if (x == "") {
for (j = 0; j < gmarkers.length; j++) {
gmarkers[j].setMap(null);
}
}
}
});
});
【问题讨论】:
-
您有一个名为
LocateEvent()的方法,但@Url.Action("Locate", "Events")在EventController中调用了一个名为Locate()的方法。LocateEvent()方法返回 html,但您指定了data: 'json',ajax 选项。使用浏览器工具调试代码并检查控制台中的错误消息。 -
我已更新代码,但标记不显示
-
GE.Events.ToList();是否返回任何内容? (您刚刚初始化了一个新的默认对象)。$.each()语句输出中的console.log(value.EventName)是什么?您需要学习使用浏览器工具来调试脚本 -
我现在想弄清楚的唯一部分是如何使用 ajax 中的“JSON.stringify”从控制器传递数据
-
您不需要
JSON.stringify删除contentType: "application/json; charset=utf-8",并使用data: { location: 'x' },。在控制器中,参数string Location的值将是"x"
标签: jquery json ajax asp.net-mvc google-maps