通过Javascript返回视图MVC3将值传递给控制器

通过Javascript返回视图MVC3将值传递给控制器,javascript,asp.net-mvc-3,razor,Javascript,Asp.net Mvc 3,Razor,我是MVC的新手。我试图将使用地理定位获得的经度和纬度值传递给我的控制器,以便我可以使用这些值来识别并从数据库中提取正确的数据 这是我的Javascript function auto_locate() { alert("called from station"); navigator.geolocation.getCurrentPosition(show_map); function show_map(position) { var latitude = po

我是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并将Longitide和Latitude发送到我的控制器

您可以使用AJAX:

$.ajax({
    url: '@Url.Action("AutoLocate")',
    type: 'GET',
    data: postData,
    success: function(result) {
        // process the results from the controller
    }
});
其中
postData={纬度:纬度,经度:经度}

或者如果您有actionlink:

@Html.ActionLink("foo bar", "AutoLocate", null, null, new { id = "locateLink" })
您可以像这样对该链接进行AJAXify:

$(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;
    });
});