我是 MVC 的新手。我试图将使用地理位置获得的经度和纬度值传递给我的控制器,以便我可以使用这些值来识别并从数据库中提取正确的数据。
这是我的 JavaScript
function auto_locate() {
alert("called from station");
navigator.geolocation.getCurrentPosition(show_map);
function show_map(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var locstring = latitude.toString() + "." + longitude.toString();
var postData = { latitude: latitude, longtitude: longitude }
alert(locstring.toString());
}
}
所有这些都运行良好;
现在我需要做的是将 postData 或 locstring 传递给我的控制器。看起来像这样:
[HttpGet]
public ActionResult AutoLocate(string longitude, string latitude)
{
new MyNameSpace.Areas.Mobile.Models.Geo
{
Latitude = Convert.ToDouble(latitude),
Longitude = Convert.ToDouble(longitude)
};
// Do some work here to set up my view info then...
return View();
}
我进行了搜索和研究,但未能找到解决方案。
如何从 HTML.ActionLink 调用上面的 javascript 并将经度和纬度发送到我的控制器?
您可以使用 AJAX:
$.ajax({
url: '@Url.Action("AutoLocate")',
type: 'GET',
data: postData,
success: function(result) {
// process the results from the controller
}
});
where postData = { latitude: latitude, longtitude: longitude };
.
或者,如果您有一个操作链接:
@Html.ActionLink("foo bar", "AutoLocate", null, null, new { id = "locateLink" })
你可以像这样 AJAX 化这个链接:
$(function() {
$('#locateLink').click(function() {
var url = this.href;
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var postData = { latitude: latitude, longtitude: longitude };
$.ajax({
url: url,
type: 'GET',
data: postData,
success: function(result) {
// process the results from the controller action
}
});
});
// cancel the default redirect from the link by returning false
return false;
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)