1

How can I reference the clicked Ajax.ActionLink from within it's OnBegin function?

cshtml

@Ajax.ActionLink(
    typeName,
    "OrderQueueRows",
    new 
    {
        typeNames = Model.Name,
        includeDerivedTypes = ViewBag.IncludeDerivedTypes,
        excludeCompletedOrders = ViewBag.ExcludeCompletedOrders
    },
    new AjaxOptions {
        LoadingElementId="ajax-loading",
        OnBegin = "highlightFilter",
        UpdateTargetId = "order-queue-body"
    },
    new { @class = "show-exclusively" })

javascript

function highlightFilter() {
    $link = $(this);
    $link.css('color', 'red');
    $link.siblings().not($link).css('color', '');
}
Benjamin
  • 3,134
  • 6
  • 36
  • 57

2 Answers2

2

You cannot achieve this with the out-of-the-box Ajax.* helpers because they do not pass the element to the onBeforeSend callback. The way Microsoft implemented it, they pass the xhr object and not the element that was clicked. So one possibility is to modify the jquery.unobtrusive-ajax.js script in order to pass this information to the callback. On line 85 you will see the following inside the beforeSend callback:

result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);

All you have to do is to modify it like this:

result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(element, arguments);

and if you needed to have both the element and the xhr object inside your OnBegin callback:

result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply({ xhr: this, element: element }, arguments);

Now, your code is going to work and this will represent the element:

function highlightFilter() {
    $link = $(this);
    $link.css('color', 'red');
    $link.siblings().not($link).css('color', '');
}

Another possibility is to simply replace the Ajax.ActionLink with a standard Html.ActionLink and then write the corresponding jQuery code to subscribe to the .click event and trigger the AJAX request. Personally it's probably what I would do.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
1

This is now fixed in ASP.NET MVC 5.1, using approach from another stackoverflow question: How to use $(this) inside MVC3 Ajax.ActionLink OnBegin,OnComplete Events

Community
  • 1
  • 1
Rafał Kłys
  • 590
  • 6
  • 14