【问题标题】:Sending data from view (javascript) to controller in MVC 5在 MVC 5 中将数据从视图(javascript)发送到控制器
【发布时间】:2016-12-04 18:57:46
【问题描述】:

所以在我的索引视图中,我接收并以纬度和经度的形式显示用户的当前位置。

(function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(showPosition);
        }
    }());
    function showPosition(position) {
        $('#lat').text(position.coords.latitude);
        $('#long').text(position.coords.longitude);

    }

有没有办法将 position.coords.latitude 和 position.coordes.longitude 发送到我的索引控制器? 或者我应该让用户点击一个按钮来提交它们,比如表单?我是使用坐标的新手。

提前致谢!

【问题讨论】:

    标签: javascript c# asp.net-mvc


    【解决方案1】:

    把它放在你的 showPosition 函数中:

    var postData = { Lat: position.coords.latitude, Long: position.coords.longitude };
    $.ajax(
    {
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "AjaxTest",
        //dataType: "json",
        data: JSON.stringify(postData),
        success: function (data, status) {
            alert("Pass" + data);
        },
        error: function (ex) {
            alert("Fail" + ex);
        }
    });
    

    在您的控制器中,您需要此操作。请给它一个更好的名字:

    public JsonResult AjaxTest(Position position)
    {
        // do whatever you want here. I am simply returning the value.
        return Json("You posted: " +  position.Lat + " items.", JsonRequestBehavior.AllowGet);
    }
    

    你需要这样的模型:

    public class Position
    {
        public double Lat { get; set; }
        public double Long { get; set; }
    }
    

    【讨论】:

    • 我现在在运行应用程序时收到此警报:i.imgur.com/n12Jy15.png
    • 因为您需要更改发布到的网址。您是否在生成视图的同一控制器中创建了该操作?如果不是,您必须指定网址。我只是输入了动作的名称,因为视图是从同一个控制器生成的。
    • 您有一个名为 IndexController 的控制器?你确定吗?您是否创建了我在 IndexController 的答案中发布的操作,并且您也从 IndexController 提供视图?这是不可能的,因为那必须奏效。您的网址不正确。此外,如果您在行动中做其他工作,那可能会失败。首先使用我的代码,一旦它工作,然后修改操作方法代码。
    • 对不起,控制器名为 HomeController,但里面有一个 Index、About 和 Contact 的任务。我发现了其他一些奇怪的行为。如果我将 postData 更改为位置,那么它只能工作一次。如果我想让它再次工作,我将它改回 postData 并运行它,但它只工作一次,这是怎么回事?
    • 好的,这些都是您遇到的所有其他问题。将您的视图和控制器代码here 并与我分享链接。我去看看。
    【解决方案2】:

    如果您可以作为获取请求发送,那么您可以将 lat 和 long 格式化为查询字符串。然后使用window.location 将浏览器重定向到您想要的任何路线。例如

    Window.location.href = querystring
    

    将查询字符串附加到现有路由...或者如果您只能提取现有路由的一部分(仅像域)并将附加段与查询字符串一起附加。结帐window.location 了解所有各种选项。

    【讨论】:

      猜你喜欢
      • 2014-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2017-10-23
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多