public IActionResult Post([FromBody] ProductPaginationParams ProductPaginationParam) { ProductPagination Pagi = new ProductPagination(); List <Products> Prod = new List <Products>(); if (String.IsNullOrEmpty(ProductPaginationParam.order)) { Prod = context.Products.OrderByDescending(s => s.Name).ToList(); if (!String.IsNullOrEmpty(ProductPaginationParam.SearchParam)) { Prod = context.Products.OrderBy(s => s.Name).ToList().Where(x => x.Name.Contains(ProductPaginationParam.SearchParam)).ToList(); } else { Prod = context.Products.OrderBy(s => s.Name).ToList(); } } else if (ProductPaginationParam.order.Equals("Likes")) { Prod = context.Products.OrderByDescending(s => s.likes).ToList(); if (!String.IsNullOrEmpty(ProductPaginationParam.SearchParam)) { Prod = context.Products.OrderBy(s => s.likes).ToList().Where(x => x.Name.Contains(ProductPaginationParam.SearchParam)).ToList(); } else { Prod = context.Products.OrderBy(s => s.likes).ToList(); } } Pagi.total = Prod.Count(); Pagi.Products = Prod.Skip((ProductPaginationParam.pageNumber - 1) * ProductPaginationParam.pageSize).Take(ProductPaginationParam.pageSize).ToList(); Pagi.Products.ForEach(x => x.links = "/api/Products/" + x.Id.ToString()); if (Pagi == null) { return(NotFound()); } return(Ok(Pagi)); }
public async Task <ProductPagination> GetPaginatedProductsAsync(int page = 1, string search = null) { // Count all products var totalProducts = await _repository.CountAllProductsAsync(search); // Calculate how many pages the products will be split into var totalPages = CalculateTotalPaginationPages(totalProducts, PRODUCTS_PER_PAGE); // If user tries to view a page past pagination-range or totalProducts is 0, return an empty view if (totalProducts == 0 || page > totalPages) { return(null); } // Set default paging to page 1 if user is trying to manipulate the starting point below 1 int currentPage = (page < 1) ? 1 : page; // Get products from selected page based on page number from query-string var products = await _repository.GetPaginatedProductsAsync(currentPage, PRODUCTS_PER_PAGE, search); var maxLinks = (MAX_PAGINATION_LINKS > totalPages) ? totalPages : MAX_PAGINATION_LINKS; var offset = CalculatePaginationOffset(totalPages, currentPage, maxLinks); // Instantiate a new Pagination-object var pagination = new ProductPagination() { PaginationData = new PaginationData() { PaginationStart = offset, // Start pagination link PaginationLimit = offset + (maxLinks - 1), // Max number of pagination-links to be displayed TotalPages = totalPages, // Total amount of pages CurrentPage = currentPage, // Current page visitor is viewing TotalProducts = totalProducts // Total amount of products }, Products = products }; return(pagination); }