Jquery 如何在MVC3 Ajax.ActionLink OnBegin、OnComplete事件中使用$(this)
我的控制器创建一个链接列表,如下所示Jquery 如何在MVC3 Ajax.ActionLink OnBegin、OnComplete事件中使用$(this),jquery,asp.net-mvc-3,unobtrusive-ajax,Jquery,Asp.net Mvc 3,Unobtrusive Ajax,我的控制器创建一个链接列表,如下所示 <ul id="MainMenu"> @foreach (var item in Model.MenuItems) { <li>@Ajax.ActionLink(item.Caption, item.ActionName, item.ControllerName, new AjaxOptions { UpdateTargetId = "pageBody", OnB
<ul id="MainMenu">
@foreach (var item in Model.MenuItems)
{
<li>@Ajax.ActionLink(item.Caption,
item.ActionName,
item.ControllerName,
new AjaxOptions
{
UpdateTargetId = "pageBody",
OnBegin = "BeginUpdatePage",
OnComplete = "EndUpdatePage",
OnFailure = "FailUpdatePage"
})
</li>
}
</ul>
function BeginUpdatePage() {
$("#MainMenu li").removeClass('selected');
$(this).parent().addClass('selected');
$("#pageBody").fadeTo('slow', 0.5);
}
function EndUpdatePage() {
$("#pageBody").fadeTo('slow', 1);
}
function FailUpdatePage() {
alert('There has been an error loading this page please try again.');
}
在BeginUpdatePage函数中,第1行和第3行可以很好地执行,但第2行“$(this).parent().addClass('selected');”没有明显地执行任何操作。。。(我已经在css中声明了该类)
我看过Jquery文档()它说“this”是被点击的元素。我还签入了默认项目中的“jquery.unobtrusiveajax.js”。这个文件在执行我的函数时也传递“This”
"result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this,arguments);"
我在这里做错了什么。。。我见过有人使用这种技术,但我一整天都在失败
如何在Begin、complete函数中访问单击的元素。您可以尝试如下方式传递它:
OnBegin = "function() { BeginUpdatePage(this); }"
function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = element.getAttribute("data-ajax-loading-duration") || 0;
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(element, arguments);
if (result !== false) {
loading.show(duration);
}
return result;
},
complete: function () {
loading.hide(duration);
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(element, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(element, arguments);
},
error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
});
options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
options.type = "POST";
options.data.push({ name: "X-HTTP-Method-Override", value: method });
}
$.ajax(options);
}
然后:
function BeginUpdatePage(element) {
$("#MainMenu li").removeClass('selected');
$(element).parent().addClass('selected');
$("#pageBody").fadeTo('slow', 0.5);
}
$(function() {
$('.someLink').click(function() {
var link = $(this);
$.ajax({
url: this.href,
beforeSend: function() {
$("#MainMenu li").removeClass('selected');
$(link).parent().addClass('selected');
$("#pageBody").fadeTo('slow', 0.5);
},
complete: function() {
$("#pageBody").fadeTo('slow', 1);
},
success: function(result) {
$('#pageBody').html(result);
},
error: function() {
alert('There has been an error loading this page please try again.');
}
});
return false;
});
});
或者只使用jQuery而不使用任何Ajax.
stuff:
<ul id="MainMenu">
@foreach (var item in Model.MenuItems)
{
<li>
@Html.ActionLink(
item.Caption,
item.ActionName,
item.ControllerName,
null,
new { @class = "someLink" }
)
</li>
}
</ul>
谢谢大家的建议,Darin,虽然你的解决方案工作得很好,但我想尝试使用内置的Ajax实用程序 在查看并检查了“jquery.unobtrusive ajax.js”之后,我找到了一个解决办法。这与其说是正确的使用,不如说是一个黑客行为。我不知道是谁把“jquery.unobtrusive ajax.js”文件放在一起的,但是如果有人知道如何给他们发电子邮件,也许可以给他们发一个指向此页面的链接:-) 这是“jquery.unobtrusiveajax.js”的有趣部分 在此函数中,“函数异步请求(元素、选项)” 当这段代码在发送、完成、出错之前对每个步骤调用该方法时,它会传入两个peram,“this”和“arguments” Wich可以创建,但在上下文中“this”是XHR(XMLHttpRequest)而不是单击的元素。。。另外,通过检查函数头,您可以看到它将XHR对象作为第一个peram传递。那么为什么我们也需要它作为调用上下文呢 我的解决方案。。。更改“jquery.unobtrusive ajax.js”和“jquery.unobtrusive-ajax-min.js”文件 与其在apply方法上传递“this”(XHR),不如改为发送实际的元素 因此,整个函数现在如下所示:
OnBegin = "function() { BeginUpdatePage(this); }"
function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = element.getAttribute("data-ajax-loading-duration") || 0;
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(element, arguments);
if (result !== false) {
loading.show(duration);
}
return result;
},
complete: function () {
loading.hide(duration);
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(element, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(element, arguments);
},
error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
});
options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
options.type = "POST";
options.data.push({ name: "X-HTTP-Method-Override", value: method });
}
$.ajax(options);
}
现在,当您创建处理这些事件的函数时,您可以使用“this”来获取实际的元素
例如:
function BeginUpdatePage(xhr) {
$("#MainMenu li").removeClass('selected');
$(this).parent().addClass('selected');
$("#pageBody").fadeTo('slow', 0.5);
}
function EndUpdatePage(xhr,status) {
$("#pageBody").fadeTo('slow', 1);
}
function FailUpdatePage(data,status,xhr) {
alert('There has been an error loading this page please try again.');
}
现在对于一些人来说,使用Darin的解决方案更容易,只需编写自己的Jquery来处理点击事件,嘿,你可能可以更好地控制这一切
但是我相信内置的东西也应该起作用。不必把它弄乱。
所以我希望有人能证明我错了,事实上有更好的方法来做到这一点,或者把这个脚本放在一起的人可以改变它
除非他们有充分的理由这样做?欢迎解释:-)
再次感谢所有对这个问题有好建议的人
我希望这对将来的人们有所帮助。检查event.srcelment如何?我有另一个解决方案,它使用AJAX URL选择单击的原始链接。只有当只有一个ActionLink具有准确的URL时,此解决方案才能正常工作:
function BeginUpdatePage() {
// Get the URL that will be posted to
var targetUrl = this.url;
var sourceLink = null;
// loop through all action links applicable
$('#MainMenu a').each(function () {
var href = $(this).attr('href');
// the targetUrl contains the entire URL - including http://
// so we need to do an indexOf to see if the href is contained
// within the target URL
if (targetUrl.indexOf(href) > -1) {
sourceLink = $(this);
return false;
}
});
// we've now got the link that was clicked - do with it as you wish...
sourceLink.parent().addClass('selected');
}
更新2014年1月20日:正式3.1版的低调ajax脚本包含了这一变化,并与MVC 5.1版本(1月17日)同时发布。去看看吧:-) 原始响应 不久前,我偶然发现了你想要的结果。做起来很简单 在jquery.unobtrusive-ajax.js文件的大约第100行,添加这一行代码
options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
options.context = element; // <--- Add this line
method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
options.type = "POST";
options.data.push({ name: "X-HTTP-Method-Override", value: method });
}
options.data.push({name:“X-request-With”,value:“XMLHttpRequest”});
options.context=element;//如果类“selected”真的没有被添加,你有没有检查firebug?Microsoft AJAX与JQuery不同,所以我认为你看的文档是错误的。+1检查firebug。您可以中断回调脚本并在控制台中检查这个。@Ogz向导-它肯定不会添加类。MicrosoftAjax扩展了Jquery。它使用Jquery.Ajax()发送请求。如果您查看“jquery.unobtrusive ajax.js”,您可以看到“function asyncRequest(元素,选项)”这是它调用您分配给onBegin属性的函数的地方。。。现在我已经看过了,我可以看到它将“this”设置为XHR。@MichaelLake-我应该更好地表达我的评论。我想确保AjaxOptions回调(OnBegin、OnComplete、OnFailure)传递的参数与您在jQuery函数中预期的参数相同。干杯谢谢你在这里的意见,我试着投票支持你,但我还没有足够的声誉:-(因此,我将在这里发表我的评论。感谢您的帮助,您的解决方案本可以工作,但我希望使用内置的东西使其工作。感谢您对此进行跟踪。我们计划很快对此进行查看。我看到今天已更改。感谢更新!!期待正式发布:-)+1:刚刚更新到3.1,此
现在是单击的UI项。太棒了!感谢您让我们知道此更改。现在应该是正确的答案。