我们决定在我们的应用程序中使用服务器端分页。实现非常简单:
假设我们在服务器端有这样的搜索操作:
[HttpGet] public ActionResult GetPeopleByName(String term, Int32 itemsPerPage = 10, Int32 page = 0) { var matches = this.people.Where(i => i.Name.Contains(term)); return Json( data: new { people = matches.Skip(itemsPerPage * page).Take(itemsPerPage).OrderBy(i => i.Name), total = matches.Count() }, behavior: JsonRequestBehavior.AllowGet ); }
在客户端我们有一个
subscriptionHolderController
:app.controller('subscriptionHolderController', ['$scope', '$http', function($scope, $http) { $scope.matches = []; $scope.itemsPerPage = 5; $scope.currentPage = 0; $scope.searchTerm = ''; // $scope.prevPage = function() { ... }; // $scope.prevPageDisabled = function() { ... }; // $scope.nextPage = function() { ... }; // $scope.nextPageDisabled = function() { ... }; $scope.pageCount = function() { return Math.ceil($scope.totalPages / $scope.itemsPerPage); }; $scope.$watch('currentPage', function() { $scope.search(); }); $scope.search = function() { if($scope.searchTerm === '') return; // initiate a GET-request with params: { page: $scope.currentPage, term: $scope.searchTerm, itemsPerPage: $scope.itemsPerPage } } $scope.matchesFound = function () { return $scope.matches.length > 0; } }]);
问题
结果我们有一个简单的搜索框
。但是我们的应用程序需要另一种类型的搜索以及一些附加功能,它不使用搜索词,并且其结果集应该按照与上面显示的相同的方式进行分页。
如何为不同类型的搜索重用分页逻辑?
最佳答案
在服务器端,您可以返回一个通用类,该类将保存您的数据(行总数)。
public class PagedResult<T>
{
public PagedResult(IEnumerable<T> data, long total)
{
Data = data;
Total = total;
}
public PagedResult()
{
}
public IEnumerable<T> Data { get; set; }
public long Total { get; set; }
}
您还可以抽象任何函数的输入参数,例如:
public class PageInfo
{
public int Page { get; set; }
public int PageSize { get; set; }
public int Skip
{
get
{
return PageSize*(Page - 1);
}
}
public PageInfo(int page, int pageSize)
{
Page = page;
PageSize = pageSize;
}
}
一个实际的例子可能是这样的:
[HttpGet]
public ActionResult GetPeopleByName(String term, PageInfo pageinfo) {
var matches = this.people.Where(i => i.Name.Contains(term));
var pagedResult = new PagedResult<AnySearchType>{
data = matches.Skip(pageinfo.skip).Take(pageinfo.size).OrderBy(i => i.Name),
total = matches.Count()
};
return Json(
data: pagedResult,
behavior: JsonRequestBehavior.AllowGet
);
}
在客户端,您可以使用指令通过传递以下参数来抽象分页逻辑:
查看
<div class="box-content" scroll-pager="pagerConfig">
your data
<div>
Controller :
您可以传递一些配置,例如:
$scope.pagerConfig = {
pageSize: 10,
data: 'model.Data', // some text reference to your model
total: 'model.Total', // some text reference to your model
currentPage: 1,
searchParamName: 'Text',// some text reference to your model
resource: projectResource,// pass a resource object
success: function (data, page, total) {
}
};
关于c# - 如何使搜索/分页在我的应用程序中可重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25680423/