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

3

我是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 并将经度和纬度传递给我的控制器?
1个回答

5
您可以使用AJAX:
$.ajax({
    url: '@Url.Action("AutoLocate")',
    type: 'GET',
    data: postData,
    success: function(result) {
        // process the results from the controller
    }
});

这里的postData = { latitude: latitude, longtitude: longitude }是指post请求的数据,包含经度和纬度信息。

如果你有一个actionlink:

@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;
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接