razor-pagesasp.net-core-mvc-2.0

Pagination system in asp.net core 2.0 mvc


I want to create for my project a common pagination component for all my pages which contains a listing.

I used to work with old-school webforms and i am not sure to work with best practice in asp.net mvc core.

I have read this documentation which is great from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page#add-paging-functionality-to-the-students-index-page

I have put PaginatedList class in my project.

Everything works great.

But i want to put html stuff for pagination in a partial view (in order to factorize html code):

@model PaginatedList<T>

@{
    var prevDisabled = !Model.HasPreviousPage ? "disabled" : "";
    var nextDisabled = !Model.HasNextPage ? "disabled" : "";
}

<a asp-action="Index"
   asp-route-param1="@ViewData["param1"]"
   asp-route-page="@(Model.PageIndex - 1)"
   class="btn btn-default @prevDisabled">
    Previous
</a>
<a asp-action="Index"
   asp-route-param1="@ViewData["param1"]"
   asp-route-page="@(Model.PageIndex + 1)"
   class="btn btn-default @nextDisabled">
    Next
</a>

Then, i want to put this line at the bottom of each listing page:

@Html.Partial("~/Views/Shared/_pagination.cshtml", Model)

I have 2 problems:

Thanks


Solution

  • Sort of an old question but... I use this to render the partial at the top and bottom:

     @await Html.PartialAsync("_pagination.cshtml")
    

    Then just use the same model as the main page in your _pagination.cshtml page:

     @model youproject.Pages.yourpageModel;
    

    ....

    @{
        var prevDisabled = !Model.PaginatedInventory.HasPreviousPage ? "disabled" : "";
        var nextDisabled = !Model.PaginatedInventory.HasNextPage ? "disabled" : "";
        var SortOrderDir = Model.CurrentSortDir;
        var numberOfPages = Model.PaginatedInventory.TotalPages;
        var CurrentPageIndex = Model.PaginatedInventory.PageIndex;
    
    
        int CurrentLimit = Model.IntegerCurrentLimit;
        int start = ((CurrentPageIndex - 7) > 0) ? CurrentPageIndex - 7 : 0;
        int end = ((CurrentPageIndex + 7) < numberOfPages) ? CurrentPageIndex + 7 : numberOfPages;
    
    }
    

    etc... the pagemodel (yourpagemodel.cs file) creates "PaginatedInventory":

    public PaginatedList<InventoryItem> PaginatedInventory { get; set; }
    

    ...

      PaginatedInventory = await PaginatedList<InventoryItem>.CreateAsync(
                    Items,CurrentPageIndex, IntegerCurrentLimit);
    

    The type is already defined in the model.