使用 MVC3 从 ActionLink 将值传递给 Javascript 函数



我必须从视图中调用这个javascript函数:

$("#addCompositionItem").click(function (carrier) {
        $.mobile.loading('show');
        $.ajax({
            url: this.href,
            cache: false,
            success: function (html) {
                $("#Compositions"+carrier).append(html);
                $("#newServicePageContent").trigger("create");
                $.mobile.loading('hide');
            }
        });
        return false;
    });

如您所见,carrier 是用于在不同容器中加载 html 部分的参数。如何从操作链接传递此值?我正在尝试:

@Html.ActionLink("Text", "ActionName", "ControllerName", new { id = "addCompositionItem", carrier="XYZ",type = "submit" })

但没有成功

我理解正在发生的事情的方式是,您正在使用 HTML 帮助程序生成锚标记,然后通过 JavaScript 附加来处理click事件。在处理程序中,您希望能够从原始链接获取一段数据。

我的建议是使用 HTML 数据注释来保存数据。就像您现在一样,您的参数只是通过路由参数编码到 href 属性中。如果您将其移动到 html 属性并使用data_carrier框架将生成您的锚标记,如下所示(不是下划线到连字符是自动转换):

@Html.ActionLink("Text", "ActionName", "ControllerName", new { /*route params*/}, new { data_carrier="..." })

应该导致类似以下内容:

<a href='...' data-carrier='...'>...</a>

然后在你的JavaScript中,不要试图将值作为参数获取,只需使用jQuery data()方法或任何你喜欢的原始JavaScript来访问该属性。

var carrier = $(this).data('carrier');

我认为这将涵盖您的用例。

下面的代码片段是由EndangeredMassa在这个SO问题中给出的。 它应该解决你的问题。

<html>
<head>
<script type="text/javascript">
    // Wait for the page to load first
    window.onload = function() {
      //Get a reference to the link on the page
      // with an id of "mylink"
      var a = document.getElementById("mylink");
      //Set code to run when the link is clicked
      // by assigning a function to "onclick"
      a.onclick = function() {
        // Your code here...
        //If you don't want the link to actually 
        // redirect the browser to another page,
        // "google.com" in our example here, then
        // return false at the end of this block.
        // Note that this also prevents event bubbling,
        // which is probably what we want here, but won't 
        // always be the case.
        return false;
      }
    }
</script>
</head>
<body>
    <a id="mylink" href="http://www.google.com">linky</a>        
</body>
</html>

最新更新