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

时间:2011-07-23 21:31:46

标签: jquery asp.net-mvc-3 razor unobtrusive-javascript

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

@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并切换该元素上的类。我不确定如何将它连接起来。我错过了什么?

1 个答案:

答案 0 :(得分:7)

首先修复你的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');
}

就个人而言,我不是Ajax.*助手的粉丝。我使用了一种替代方法,该方法由标准HTML ActionLink

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

我在一个单独的javascript文件中不引人注意地使用AJAXify:

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