如何告诉Ajax.ActionLink OnSuccess回调哪个元素启动了Ajax [英] How to tell Ajax.ActionLink OnSuccess callback which element initiated the ajax

查看:82
本文介绍了如何告诉Ajax.ActionLink OnSuccess回调哪个元素启动了Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want my razor view to look something like this

@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看起来像这样

and my javascript to look something like this

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

这个想法是,如果我单击A链接,它将执行ajax并切换该元素上的类.我不确定到底该如何连接它.我想念什么?

the idea being that if I click the A link, it'll do the ajax and toggle the class on that element. I'm not sure exactly how to hook it up though. What am I missing?

推荐答案

由于您的Ajax.ActionLink重载无法编译,因此请先对其进行修复.

First fix your Ajax.ActionLink overload as yours won't compile.

要传递参数,您可以执行以下操作:

And to pass parameters you could do this:

@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组成的替代方法:

Personally I am not a fan of the Ajax.* helpers. I use an alternative approach which consists of a standard HTML ActionLink:

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

我毫不客气地在单独的javascript文件中AJAXify:

which I unobtrusively AJAXify in a separate javascript file:

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

这篇关于如何告诉Ajax.ActionLink OnSuccess回调哪个元素启动了Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆