ASP.NET MVC 2 Html.ActionLink with JavaScript variable

六月ゝ 毕业季﹏ 提交于 2019-12-01 03:39:20

问题


<%: 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?


回答1:


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;
    });
});


来源:https://stackoverflow.com/questions/5067813/asp-net-mvc-2-html-actionlink-with-javascript-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!