I have a table that lists users that are registered at my website. The page contains a textbox that acts like a filter: as soon as a user types something into the textbox, the table is filtered, so only users are retrieved whose name contains the value of the textbox.
This is done using jquery. It posts to a controller action, which in turn returns some json, which is parsed so the user list is updated. This works great.
Now, this user list must have pagination in it. Pretty simple, only previous and next buttons, which will fetch the previous or next 10 results. These are Ajax.RouteLinks. However, I must of course post the correct pagenumber to the controller action, so it knows which users to retrieve. Herein lies the problem: I don't know how to do this. Where do I get this value from? I have tried:
- Setting a ViewData key in the controller, but as I return a Json result, this value is never updated.
- I tried adding the previous and next pagenumbers in the json result, but then what? The Ajax.RouteLink generates a long link with all sorts of data, I don't see how I can use jquery to easily modify some parameter in there
- I tried to generate the link server-side and add that to Json, but I can't access the ViewContext from the controller, which is needed to instantiate a new AjaxHelper in my action. Or whatever.
If it helps, below is some of the code. As you can see in the jquery code, the correct pagenumbers ARE alerted there. But how to get that into the routelink? Or any other smart way to achieve this? Thanks!
jquery code:
function searchUsers() {
$.post("/Search/Users", $("#searchUsersForm").serialize(), function(data) {
$('#searchResultsTable tr').remove();
$.each(data.Result, function(index, result) {
$('#searchResultsTable').append('<tr><td>' + result.Username + '</td></tr>');
});
if (data.PreviousPageNumber != null)
alert('previous: ' + data.PreviousPageNumber);
if (data.NextPageNumber != null) {
alert('next: ' + data.NextPageNumber);
}
}, "json");
}
Html:
<form id="searchUsersForm">
<input type="text" name="userName" id="userName" onkeyup="searchUsers()" onchange="searchUsers()" />
</form>
<%
Response.Write("<span class='pagingPrevious'>" + Ajax.RouteLink("< previous", "User-List", new { pageNumber = ((int?)ViewData["PreviousPageNumber"]).Value }, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "profilePageInbox" }) + "</span>");
Response.Write("<span class='pagingNext'>" + Ajax.RouteLink("next >", "User-List", new { pageNumber = ((int?)ViewData["NextPageNumber"]).Value }, new AjaxOptions() { InsertionMode = InsertionMode.Replace, UpdateTargetId = "profilePageInbox" }) + "</span>");
%>
Controller:
public ActionResult SearchUsers(string userName)
{
// fetch data
ViewData["PreviousPageNumber"] = userViewModel.PreviousPageNumber; // does not work
ViewData["NextPageNumber"] = userViewModel.NextPageNumber; // does not work
return this.Json(userViewModel);
}