ActionLink in jQuery
本文关键字:jQuery in ActionLink | 更新日期: 2023-09-27 18:20:06
这是我的方法:
$(document).ready(function () {
$('td.clickableCell').click(function () {
var currentObject = null;
currentObject = $(this).text();
@Html.ActionLink("GetThis", "Get", new {theName = currentObject} )
});
});
但它表示currentObject在当前上下文中不存在。如何解决此问题?
您应该使用jQuery.get函数而不是@Html.ActionLink
`@Html.ActionLink在服务器上运行,而javascript在客户端上运行。
$(document).ready(function () {
$('td.clickableCell').click(function () {
var currentObject = $(this).text();
$.get('@Url.Action("GetThis", "Get")', {theName : currentObject});
});
});
Url.Action
在服务器上呈现,并将为您提供适当的url。$.get
将在客户端上运行get
请求。
请记住,如果此javascript位于.js
文件中,则不会运行Url.Action
。在这种情况下,您可能只想用/Get/GetThis
替换它,或者在页面上的隐藏字段中呈现url,并在.js
文件中获取隐藏字段的值。
您需要一个看起来像这样的操作方法来访问参数:
public ActionResult GetThis(string theName)
{
// manipulate theName
return View();
}
currentObject
是一个JavaScriptString对象,您正试图将其传递到服务器端代码中。如果你需要在客户端这样做,
$(function () {
$('td.clickableCell').click(function () {
var currentObject = $(this).text();
// find the anchor element that you need to change,
// then change the property on it to the value
// of currentObject
$('a').attr('title', currentObject);
});
});
或者,您可能需要以某种方式将值发送到服务器。如果上面的JavaScript在Razor视图中,则
$(function () {
$('td.clickableCell').click(function () {
var currentObject = $(this).text();
// make a HTTP GET request and pass currentObject as a queryparam
window.location = '@Url.Action("Action", "Controller")' + '?theName=' + encodeURIComponent(currentObject);
});
});
'@Url.Action("Action", "Controller")'
部分将在服务器端进行评估,并由UrlHelper解析为路由到该控制器操作的URL。我们将这个值放在单引号中,因为我们需要在客户端的JavaScript变量中使用它。然后我们添加currentObject
作为查询参数(同时对其进行编码)。
您正在混合客户端代码和服务器端代码。在任何东西发送到客户端之前,这一行正在服务器上执行:
@Html.ActionLink("GetThis", "Get", new {theName = currentObject} )
这条线本身就引用了一些不存在的东西。currentObject
只有在客户端上用JavaScript创建后才会存在。从服务器的角度来看,JavaScript代码只不过是文本。