我有一个可以搜索的项目列表,并且页面有分页。当输入搜索查询时,部分视图会正确加载(AJAX)。但是,当您使用分页时,它会触发非 ajax 请求(重新加载整个页面,并且标头中没有 XmlHttpRequest 标志)。
这是什么原因造成的?
$(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>
根据教程,这行代码应该已经解决了您不能将分页用于结果集的问题。
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);
}
View
当我在 the和call处都设置断点时PartialView
,它会在我使用分页时命中View
(从而导致每次都显示所有数据)。为什么我的请求不被视为 AJAX 请求?