简体   繁体   中英

Can I pass a Javascript variable in an @Ajax.Actionlink in asp.net-mvc 3?

I have the following Javascript code:

var idJS;

$('.disp').click(function () { 
    idJS = $(this).attr("id");   
})

And then I want to do this:

@Ajax.ActionLink("myMethod", "myMethod", "HomeController", new { id = idJS },
  new AjaxOptions() { HttpMethod = "Get", UpdateTargetId = "myDiv" })

Is it possible to do this?

This is not possible to do because Razor view code is rendered when the page it loaded, so all that code is resolved (transformed to HTML) before the javascript can even execute.

You can however use Javascript to change properties of a link, like the following for example (using JQuery though I am afraid, look up a javascript equivalent if need be)

$("a").attr("href", "/Home/myMethod/" + idJS);

ok I will look it up then, javascript only:

document.getElementById("link").href = "/Home/myMethod/" + idJS;

No. Server side and client side are two very different things. The server side is rendered before even reaching the client. By the time $(document).ready() is fired, the server is finished.

What you can do is change the id of the link with jQuery. With a little more information, I would be able to help more, but it's a simple thing to change attribute with jQuery.

I would set the id to be hard coded, like "ajaxBtn" or something, then, in your click even for .disp, change a data attribute to what you need it to be. However, without more data, I can't know for sure exactly why you're needing to set the id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM