Call JavaScript function from PagedListPager

Dumisani picture Dumisani · Feb 6, 2014 · Viewed 7.5k times · Source

Is it possible to call a JavaScript function from within @Html.PagedListPager(in here) ?

I have a button which calls the following function and performs all its supposed to with ease:

function fetchResults() {
    $.get('@Url.Action("Search", "Notifications")',
        {
            device: "Device"
        },
        function (data) {
            $('#results').html(data);
        })
};

Now how can I do the same when I click on a page number on my PagedListPager?

Currently my pager reloads the page and that's the main thing I want to avoid.

This is my Pager:

@Html.PagedListPager((IPagedList)ViewBag.NotificationsPage, page => 
    Url.Action("Search", "Notifications", new
    {
        device = "Device",
        page = page
    }),
    PagedListRenderOptions.PageNumbersOnly)

Perhaps there's a much better way to do this. Help will be appreciated.

Answer

Darin Dimitrov picture Darin Dimitrov · Feb 6, 2014

All that this @Html.PagedListPager helper does is spit some HTML containing links to perform the pagination. So you could subscribe to the click event of those links and AJAXify them:

$(document).on('click', 'a', function() {
    $.ajax({
        url: this.href,
        type: 'GET',
        cache: false,
        success: function(result) {
            $('#results').html(result);
        }
    });
    return false;
});

Important things to note:

  • I have subscribed to the click event in a lively manner. This means that if we replace the links in the success callback of the AJAX request, this click event handler will continue to work
  • You might want to adjust the $(document).on('click', 'a', function() { selector which is pretty inclusive and target only the links generated by this pager. For example look if they are not inside some containing div or something in which case you could use something along the lines of $('.pager').on('click', 'a', function() {.
  • Inside the success callback you might need to adapt the $('#results') selector to target the div containing the actual results which will get refreshed with the partial HTML returned by your controller action.
  • Talking about partial HTML and controller action you will obviously need to adapt the controller action that gets invoked in the AJAX request to return a PartialView instead of a full View containing only the updated records and new pagination links.