问题
I have a list of items which can be searched and the page has pagination. When a search query is entered the partial view gets loaded correctly (AJAX). However, when you use the pagination, it fires a non-ajax request (entire page gets reloaded and no XmlHttpRequest flag in the header).
What causes this?
$(function () {
// Adds Ajax to pagination of search results
var getPage = function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
type: "get",
data: $("form").serialize()
};
$.ajax(options).done(function (data) {
var $target = $a.parents("div.pagedlist").attr("data-nn-target");
var $newHtml = $(data);
$target.html($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$(".main-content").on("click", ".pagedlist a", getPage);
});
<form method="GET" action='@Url.Action("Index", "Show")' data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="@Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
<table></table> // content
<div class="pagedlist" data-nn-target="#contentlist">
@Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.MinimalWithItemCountText)
</div>
</div>
According to the tutorial, this line of code should've solved the issue where you can't use the pagination for a resultset.
data: $("form").serialize()
public ActionResult Index(string query = "", int page = 1) {
IPagedList<ShowViewModel> model;
if (Request.IsAjaxRequest()) {
model = ViewModelFactory.Instance.CreateShowViewModels(_showRepository.GetShows()
.Where(
x =>
x.Title.ToLower()
.Contains(
query.ToLower())))
.OrderByDescending(x => x.LatestRelease).ToList().ToPagedList(page, 15);
ViewBag.Search = query;
return PartialView("_Shows", model);
}
model = ViewModelFactory.Instance.CreateShowViewModels(_showRepository.GetShows()).OrderByDescending(x => x.LatestRelease).ToList().ToPagedList(page, 15);
ViewBag.Search = null;
return View(model);
}
When I put a breakpoint at both the View
and the PartialView
call, it hits the View
whenever I use pagination (and thus causing all data to be displayed each time). Why aren't my requests seen as AJAX ones?
回答1:
Make sure that .main-content
is a true ancestor of your pagination links; otherwise, the event delgation $(".main-content").on("click", ".pagedlist a", getPage)
won't work.
Update:
Follow-up issue. this:
var $target = $a.parents("div.pagedlist").attr("data-nn-target");
...should be this instead:
var $target = $($a.parents("div.pagedlist").attr("data-nn-target"));
This is because attr("data-nn-target")
will just give you the selector, not a jQuery object using that selector.
来源:https://stackoverflow.com/questions/17369597/ajax-request-isnt-recognized-as-such