![](/img/trans.png)
[英]How to traverse a Dictionary that is returned from JsonResult method?
[英]Passing a value from a JsonResult method to another method
在我的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);
}
如果在控制器中声明了变量,则可以解释为什么它们为零。
控制器是根据每个请求创建的。 因此,如果您点击AjaxTest
并设置经度/纬度,则当JsonResult
返回到ajax调用时,将处置带有您的变量的控制器。 尝试使用Session
而不是变量。 看这里 。
您可以使用TempData
将数据放入AjaxTest
操作中,如下所示:
public ActionResult AjaxTest(Position postData)
{
this.TempData["lat"] = postData.Lat;
this.TempData["lng"] = postData.Long;
return RedirectToAction("Index");
}
在索引操作中,您可以像这样检索数据:
public async Task<ActionResult> Index()
{
var lat = this.TempData["lat"];
var lng = this.TempData["lng"];
return View(parkingLot);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.