Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 2 Html.ActionLink with JavaScript variable

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

In the code above userId is a variable. This syntax is not right, what should it be?

like image 374
Mark Avatar asked Feb 21 '11 15:02

Mark


1 Answers

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;
    });
});
like image 169
Darin Dimitrov Avatar answered Jan 03 '23 16:01

Darin Dimitrov