【发布时间】:2016-12-06 03:33:42
【问题描述】:
在我的 HomeController 中,我有以下方法:
public JsonResult AjaxTest(Position postData)
{
Session["lat"] = postData.Lat;
Session["lng"] = postData.Long;
return Json("", JsonRequestBehavior.AllowGet);
}
如何在我的 Index 方法中设置 lat 和 lng?
如果重要的话,它是 public async Task<ActionResult> Index()。
视图中正在检索和传递用户当前坐标的脚本:
var x = document.getElementById("positionButton");
(function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
}());
function showPosition(position)
{
if (position == null) alert('Position is null');
if (position.coords == null) alert('coords is null');
$('#lat').text(position.coords.latitude);
$('#long').text(position.coords.longitude);
var postData = { Lat: position.coords.latitude, Long: position.coords.longitude };
$.ajax(
{
type: "POST",
contentType: "application/json; charset=utf-8",
url: "@Url.Action("AjaxTest", "Home")",
//dataType: "json",
data: JSON.stringify(postData)
});
}
我需要能够获得用户当前的纬度/经度才能获得到另一个位置的距离。 lat 和 lng 被声明为公共变量,为什么在 Index 方法中尝试使用坐标时它们保持为 0?
编辑,这里是Index方法:
public object x;
public async Task<ActionResult> Index()
{
x = Session["lat"];
return View(parkingLot);
}
【问题讨论】:
-
您是否在同一个请求中访问它们?
-
我不确定,Index加载并获取坐标后,将其发送到JsonResult。
-
尝试将 postData 作为对象而不是字符串传递。数据:发布数据。另一件事要检查...您是否在 javascript 上设置了调试器以确保您的 Lat 和 Long 不为 0?
-
我做了你说的那个改变,我要在方法中修改什么?不,我没有设置它
标签: javascript c# asp.net-mvc