【问题标题】:Using jquery variable as an argument for an ActionLink in .net MVC在 .net MVC 中使用 jquery 变量作为 ActionLink 的参数
【发布时间】:2012-09-05 08:14:32
【问题描述】:

只有我一个人还是真的很难在 javascript 中使用变量?

我的问题是我想将我的 javascript 函数的一些结果用于 MVC .net 控制器,但我不能!

1.- 我的 JavaScript 函数在视图上运行:

     $(document).ready(function () {
           $('#go').click(function () {
             // test for presence of geolocation
             if (navigator && navigator.geolocation) {
                 navigator.geolocation.getCurrentPosition(geo_success, geo_error);

             } else {
                 // nothing at this moment.

......

   function geo_success(position) {
         printLatLong(position.coords.latitude, position.coords.longitude);
     }

除了 printLatLong 函数,我想使用参数 position.coord.latitude 通过 Html.ActionLink 将其发送到控制器,如下所示:

    @Html.ActionLink("Link to Controller", "Action", "Controller", position.coords.latitude)

但我不能使用 position.coords.latitude ,因为现在我已经退出了这个功能。我只想在我的 ActionLink 中使用该值作为参数,这太难了吗? :(

提前感谢您的帮助。

【问题讨论】:

  • 您似乎对客户端代码和服务器端代码之间的区别感到困惑。
  • 一点也不,我想在服务器端对坐标做一些操作,只是我用客户端代码获取它们。我也应该在客户端进行计算?我不这么认为。

标签: javascript asp.net-mvc jquery controller


【解决方案1】:

只需使用 html 锚点并通过 jquery 操作 href 属性即可。

脚本:

function geo_success(position) {
    printLatLong(position.coords.latitude, position.coords.longitude);
    var url = '@Url.Action("Geo", "Home")';
    // grab the anchor and modify the url
    $("#geolink").attr("href", url += "?latitude=" + position.coords.latitude);
}

在你看来

<a id="geolink">GeoLink</a>

HomeController.cs

    public ActionResult Geo(int latitude)
    {
        throw new Exception(String.Format("Do something with: {0}", latitude));
    }

【讨论】:

  • 如果你想保留 ActionLink 助手,你可以像这样添加 id:@Html.ActionLink("Link to Controller", "Action", "Controller", new { id = "geolink " })
猜你喜欢
  • 1970-01-01
  • 2011-12-12
  • 2020-04-17
  • 1970-01-01
  • 2020-10-30
  • 2018-08-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-02
相关资源
最近更新 更多