Paging issue when trying to use AJAX
After a few hours of looking for an answer and reading numerous tutorials
on AJAX I feel it might be time to get an opinion or answer on my problem.
In the server side code I am calling a method which gets data back from a
database. The data is then stored within a session variable for later use
when filtering and searching for specific data.
When the page first loads the Index ActionResult goes through as intended
and paging works correctly. When I apply a search parameter the AJAX call
also gets hit and this returns the data. However, when I click the next
page button after the search has completed the AJAX check within the
controller isn't hit and instead bounces to the else statement.
Below is the code being used in the controller and JQuery within the view.
Please note, the JQuery is in the main view and not a separate JScript
file or Partial.
public ActionResult Index(Enums.OrderFilter? orderFilter, string
searchTerm, int? page)
{
if (Request.IsAjaxRequest())
{
List<PortalOrderHeader> customerOrders = null;
if (!string.IsNullOrEmpty(searchTerm))
{
customerOrders = GetDatabaseData.GetDataFromSession(searchTerm);
}
else
{
// work in progress
}
ViewBag.CurrentFilter = searchTerm;
var pagedList = customerOrders.ToPagedList(page ?? 1, 13);
return PartialView("_OrderResults", pagedList);
}
}
else
{
// Gets data from database on page load or if a switch statement returns
as true
customerOrders = GetDatabaseData.GetDataFromDatabaseDirectly();
}
function search() {
var searchterm = $("#search-textbox").val();
if (searchterm.length >= 2) {
$("#results").fadeOut('slow', function () {
$.ajax({
url: '@Url.Action("Index", "Orders")',
// Also tried using "url: '@Url.Action("Index", "Orders", new { page
= Model.PageNumber, searchTerm = ViewBag.CurrentFilter })'",
data: { searchTerm: searchterm },
type: 'POST',
success: function (data) {
$("#results").html(data);
},
error: function (jqXhr, textStatus, errorThrown) {
},
complete: function () {
$("#search-button").removeClass('disabled');
$("#results").fadeIn('slow');
}
});
I believe I've narrowed down the issue to the paging buttons but I've had
no luck resolving the problem. When I inspect the element after the first
ajax call the ViewBag.CurrentFilter and Model.PageNumber are within the
button, however when you press the button the else statement it seems to
forget everything it had in prior to the button being pressed.
@Html.ActionLink("Next", "Index", new{page = Model.PageNumber + 1,
searchTerm = ViewBag.CurrentFilter, filterSetting = ViewBag.FilterSetting},
new { @class = "paging", data_direction = "next" })
No comments:
Post a Comment