简体   繁体   English

我可以在asp.net-mvc 3中的@ Ajax.Actionlink中传递一个Javascript变量吗?

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

I have the following Javascript code: 我有以下Javascript代码:

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. 这是不可能的,因为Razor视图代码在它加载的页面时呈现,因此所有代码在javascript甚至可以执行之前被解析(转换为HTML)。

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) 但是,您可以使用Javascript来更改链接的属性,例如以下内容(尽管我担心使用JQuery,如果需要,请查找等效的javascript)

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

ok I will look it up then, javascript only: 好吧,我会查找它,仅限javascript:

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. 当$(document).ready()被触发时,服务器就完成了。

What you can do is change the id of the link with jQuery. 你可以做的是用jQuery更改链接的id。 With a little more information, I would be able to help more, but it's a simple thing to change attribute with jQuery. 通过更多信息,我可以提供更多帮助,但使用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. 我会将id设置为硬编码,例如“ajaxBtn”或其他内容,然后,即使是.disp,也可以将数据属性更改为您需要的数据属性。 However, without more data, I can't know for sure exactly why you're needing to set the id. 但是,如果没有更多数据,我无法确切知道您为什么需要设置ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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