Reputation: 97
Filtering by category the pages are displaying correctly. Search from a search box just give results on the first page and it shows the number of pages of the all projects.
My controller below:
public ActionResult Index(string category, string search, int page = 1)
{
var viewModel = new ProductsListViewModel();
var query = repository.Products;
if (!String.IsNullOrEmpty(category))
{
query = query.Where(p => p.Category == category);
viewModel.CurrentCategory = category;
}
if (!String.IsNullOrEmpty(search))
{
query = query.Where(p => p.Name.Contains(search) ||
p.Details.Contains(search);
viewModel.Search = search;
}
viewModel.Products = query
.OrderByDescending(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize).ToList();
viewModel.PagingInfo = new PagingInfo()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = category == null ?
repository.Products.Count() :
repository.Products.Where(e =>
e.Category == category).Count()
};
return View(viewModel);
}
my page link for the view:
<div style="padding-bottom: 10px" page-model="@Model.PagingInfo" page-action="Index" page-classes-enabled="true" page-class="btn" page-class-normal="btn-default" page-class-selected="btn-primary" page-url-category="@Model.CurrentCategory" class="btn-group pull-right">
</div>
My PagingInfo.cs is:
public int TotalItems { get; set; }
public int ItemsPerPage { get; set; }
public int CurrentPage { get; set; }
public int TotalPages =>
(int)Math.Ceiling((decimal)TotalItems / ItemsPerPage);
Upvotes: 1
Views: 5409
Reputation: 7348
You could break it up like this:
public ActionResult List(string category, string search, int page = 1)
{
var model = new ProductsListViewModel();
var query = repository.Products;
if (!String.IsNullOrEmpty(category))
{
query = query.Where(p => p.Category == category);
model.CurrentCategory = category;
}
if (!String.IsNullOrEmpty(search))
{
query = query.Where(p => p.Description.Contains(search));
model.Search = search;
}
var count = query.Count();
model.Products = query
.OrderByDescending(p => p.ProductID)
.Skip((page - 1) * PageSize)
.Take(PageSize).ToList();
model.PagingInfo = new PagingInfo()
{
CurrentPage = page,
ItemsPerPage = PageSize,
TotalItems = count
};
return View(model);
}
Upvotes: 2