如何告诉 Ajax.ActionLink OnSuccess 回调哪个元素启动了 ajax

How to tell Ajax.ActionLink OnSuccess callback which element initiated the ajax

提问人:kenwarner 提问时间:7/24/2011 更新时间:7/24/2011 访问量:13537

问:

我希望我的剃须刀视图看起来像这样

@Ajax.ActionLink("A", "Buy", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "updateLetter" }, new { id = "letter-A" })
@Ajax.ActionLink("B", "Buy", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "updateLetter" }, new { id = "letter-B" })
@Ajax.ActionLink("C", "Buy", new AjaxOptions() { HttpMethod = "Post", OnSuccess = "updateLetter" }, new { id = "letter-C" })

我的 javascript 看起来像这样

function updateLetter(letter)
{
    $("#letter-" + letter).toggleClass('selected');
}

这个想法是,如果我单击 A 链接,它将执行 ajax 并在该元素上切换类。不过,我不确定如何连接它。我错过了什么?

jquery asp.net-mvc-3 剃刀 不显眼的javascript

评论


答:

8赞 Darin Dimitrov 7/24/2011 #1

首先修复你的重载,因为你的重载不会编译。Ajax.ActionLink

要传递参数,您可以这样做:

@Ajax.ActionLink(
    "A", 
    "About", 
    null,
    new AjaxOptions { 
        HttpMethod = "POST",
        OnSuccess = "updateLetter('A')" 
    }, 
    new { 
        id = "letter_A" 
    }
)

然后:

function updateLetter(letter)
{
    $("#letter-" + letter).toggleClass('selected');
}

就我个人而言,我不喜欢帮手。我使用另一种方法,它由标准 HTML 组成:Ajax.*ActionLink

@Html.ActionLink(
    "A", 
    "About", 
    null,
    new { 
        @class = "letter"
        id = "letter_A" 
    }
)

我悄悄地将 AJAXify 放在一个单独的 javascript 文件中:

$(function() {
    $('.letter').click(function() {
        var $letter = $(this);
        $.post(this.href, function(result) {
            $letter.toggleClass('selected');
        });
    });
});