ASP.NET MVC 2 Html.ActionLink with JavaScript variable

后端 未结 1 1522
情书的邮戳
情书的邮戳 2021-01-13 04:58
<%: Html.ActionLink(\"Cancel\", \"Edit\", \"Users\", new {id = \" + userID + \"  }, null) %>

In the code above userId is a variable. This syn

相关标签:
1条回答
  • 2021-01-13 05:54

    You cannot use an HTML helper which is run on the server to use a Javascript variable which is known on the client. So you need to generate your URL with the information you dispose on the server. So all you can do on the server is this:

    <%: Html.ActionLink("Cancel", "Edit", "Users", null, new { id = "mylink" }) %>
    

    Then I suppose that on the client you are doing some javascript (ideally with jquery) and a moment comes when you want to query the server using this url and the userID you've calculated on the client. So for example you could modify the link action dynamically by appending some id:

    $(function() {
        $('#mylink').click(function() { 
            var userId = ...
            this.href = this.href + '?' + userId;
        });
    });
    

    or if you wanted to AJAXify this link:

    $(function() {
        $('#mylink').click(function() { 
            var userId = ...
            $.ajax({
                url: this.href,
                data: { id: userId },
                success: function(result) {
                    ...
                } 
            });
            return false;
        });
    });
    
    0 讨论(0)
提交回复
热议问题