jQuery 中的 ActionLink
这是我的方法:
$(document).ready(function () {
$('td.clickableCell').click(function () {
var currentObject = null;
currentObject = $(this).text();
@Html.ActionLink("GetThis", "Get", new {theName = currentObject} )
});
});
但它说 currentObject 在当前上下文中不存在。如何解决这个问题?
This is my method:
$(document).ready(function () {
$('td.clickableCell').click(function () {
var currentObject = null;
currentObject = $(this).text();
@Html.ActionLink("GetThis", "Get", new {theName = currentObject} )
});
});
but it says that currentObject doesn't exist in the current context. How to resolve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该使用 jQuery.get 而不是
@Html.ActionLink
功能。 `@Html.ActionLink 在服务器上运行,而 javascript 在客户端上运行。Url.Action
在服务器上呈现,并将为您提供适当的 url。$.get
将在客户端上运行get
请求。请记住,如果此 javascript 位于
.js
文件中,则Url.Action
将不会运行。在这种情况下,您可能只想将其替换为/Get/GetThis
或在页面上的隐藏字段中呈现 url,并获取.js 文件。
您需要一个如下所示的操作方法才能访问参数:
Instead of
@Html.ActionLink
you should use the jQuery.get function. `@Html.ActionLink is run on the server whereas the javascript is run on the client.The
Url.Action
is rendered on the server and will give you the appropriate url. The$.get
will run aget
request on the client.Keep in mind, if this javascript is in a
.js
file, theUrl.Action
will not be run. In that case you may simply want to replace it with/Get/GetThis
or render the url in a hidden field on the page and get the value of the hidden field in your.js
file.You need an action method that looks like this in order to access the parameter:
currentObject
是您尝试传递到服务器端代码的 JavaScript String 对象。如果您需要在客户端执行此操作,或者,您可能需要以某种方式将值发送到服务器。如果上面的 JavaScript 位于 Razor 视图中,则
'@Url.Action("Action", "Controller")'
部分将在服务器端进行评估并由 UrlHelper 解析到路由到该控制器操作的 URL。我们将此值放在单引号中,因为我们需要在客户端的 JavaScript 变量中使用它。然后我们添加currentObject
作为查询参数(并同时对其进行编码)。currentObject
is a JavaScript String object that you are trying to pass into server side code. If you need to do this on the client side,Alternatively, it's possible that you need to send the value to the server in some way. If the JavaScript above is within a Razor view, then
The
'@Url.Action("Action", "Controller")'
portion will have been evaluated on the server-side and been resolved by the UrlHelper to the URL to route to that controller action. We put this value in single quotes as we need to use it on the client side in a JavaScript variable. Then we addcurrentObject
as a query parameter (and encode it at the same time).您将客户端代码与服务器端代码混合在一起。在将任何内容发送到客户端之前,此行将在服务器上执行:
该行本身引用了不存在的内容。
currentObject
在客户端上用 JavaScript 创建之前不会存在。从服务器的角度来看,JavaScript 代码只不过是文本。You're mixing client-side code with server-side code. This line is being executed on the server before anything is sent to the client:
That line, by itself, references something which doesn't exist.
currentObject
won't exist until it's created in JavaScript on the client. That JavaScript code, from the perspective of the server, is nothing more than text.