通过Javascript将值传递给Controller返回查看MVC3 Razor

时间:2011-07-11 20:15:23

标签: 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 = 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?

1 个答案:

答案 0 :(得分: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 };

或者如果你有一个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;
    });
});
相关问题