How to tell Ajax.ActionLink the OnSuccess callback that ajax initiated

I want my razor 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 is that if I click on link A, it will make ajax and switch the class to this element. Although I'm not sure how to connect it. What am I missing?

+6
source share
1 answer

First fix the Ajax.ActionLink overload as yours will not compile.

And to pass parameters you can 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 Ajax.* . I use an alternative approach, which consists of 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'); }); }); }); 
+7
source

Source: https://habr.com/ru/post/893427/