通过JavaScript将值传递给控制器返回查看MVC3剃刀 [英] Passing values to Controller via Javascript return View MVC3 Razor
问题描述
我是全新到MVC。我想通过我获得使用地理定位经度和纬度值,以我的控制器,这样我就可以使用值从我的数据库识别并拉正确的数据。
I am brand new to MVC. I am trying to pass longitude and latitude values I obtain using geolocation to my controller so that I can use the values to identify and pull the correct data from my database.
下面是我的javascript
Here is my 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());
}
}
所有这一切工作正常;
All of this works fine;
现在我需要做的是通过POSTDATA或locstring我的控制器。它看起来像这样:
Now what I need to do is pass postData or locstring to my controller. Which looks like this:
[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();
}
我寻觅和研究,我一直没能找到解决的办法。
I have searched and researched and I have not been able to find a solution.
我怎么能说上面的JavaScript从HTML.ActionLink并获得Longitide和Latitude我的控制?
How can I call the javascript above from an HTML.ActionLink and get the Longitide and Latitude to my controller?
推荐答案
您可以使用AJAX:
$.ajax({
url: '@Url.Action("AutoLocate")',
type: 'GET',
data: postData,
success: function(result) {
// process the results from the controller
}
});
其中, POSTDATA = {纬度:纬度,经度:东经};
或者,如果你有一个ActionLink的:
Or if you had an actionlink:
@Html.ActionLink("foo bar", "AutoLocate", null, null, new { id = "locateLink" })
您可以AJAXify这样此链接:
you could AJAXify this link like this:
$(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;
});
});
这篇关于通过JavaScript将值传递给控制器返回查看MVC3剃刀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!