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

若如初见. 提交于 2019-12-19 06:54:16

问题


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" })

and my javascript to look something like this

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

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?


回答1:


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" 
    }
)

and then:

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

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" 
    }
)

which I unobtrusively AJAXify in a separate javascript file:

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


来源:https://stackoverflow.com/questions/6803440/how-to-tell-ajax-actionlink-onsuccess-callback-which-element-initiated-the-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!