NoPyGod
NoPyGod

Reputation: 5067

ASP.NET MVC ajax pagination with partial view

I have a search page which uses a simple ajax request to get new search results from the controller.

The controller returns the results as rendered html, so all the client script has to do is $('#results').html(data);

The html also contains paginated links.

I want to add click handlers to these paginated links inside the ajax success event handler, but I find it kind of icky to be getting the page number from the A's text property.. hypothetically, the links could read "Page 1", "Page 2", and then i'd be parsing text.

Am I doing this wrong?

Should I be generating the ajax links inside the partial view instead?

Upvotes: 0

Views: 1930

Answers (1)

Alex R.
Alex R.

Reputation: 4754

The page number can be stored as data for a element. You can refer to that data in hooking up your event handlers. Traditionally--i.e. in my old applications--I would do it like this:

<a href="#" name="myLink" data="<%: [pageNumber] %>">
  Page <%: [pageNumber] %>
</a>

Then on the jquery side (i.e., ajax callback):

$('a[name=myLink]').click( function (e) {
  e.preventDefault();
  var pageNumber = $(this).attr('data');
  // do what you have to do with the pageNumber
});

But you can (and should) refer to the jQuery data function if you are going down this route.

Upvotes: 1

Related Questions