Friday, October 11, 2019

How to implement pagination in asp.net core MVC C# (db First Approach EF-CORE) (Part-6)

Hello & As-salam u alikum ! , In this article we will learn to implement Pagination in asp.net core Razor page.

Note : For Beginner Guide Articles :

https://dotnetcorecommunity.blogspot.com/p/aspnet-core-tutorials-paracticals.html



Step# 1:  
Watch previous article for applying Search filer and display data on asp.net core view page from sql server table.


In last blog we had a Index Action method in Custom Controller which was like this .
-----------------------------------------------------------------------------------------------

[HttpGet]

        public async Task<IActionResult> Index(string sortOrder, string searchString)

        {

            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";

            ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";

            ViewData["CurrentFilter"] = searchString;


            var li = from s in db.TblUser
                     select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                li = li.Where(s => s.UUserName.Contains(searchString)
                                       || s.UEmail.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "name_desc":
                    li = li.OrderByDescending(s => s.UUserName);
                    break;
                case "Date":
                    li = li.OrderBy(s => s.UAddedDate);
                    break;
                case "date_desc":
                    li = li.OrderByDescending(s => s.UAddedDate);
                    break;
                default:
                    li = li.OrderBy(s => s.UUserName);
                    break;
            }
            return View(await li.AsNoTracking().ToListAsync());
        }
-----------------------------------------------------------------------------------------------

the above action method was perfect to sort, Search and display data from sql server table.

now I am going to make few changes for pagination in my Action method but before doing that we need to follow the step 2.

Step# 2:  
Right click on Model folder and add a new class and name it as "PaginatedList" .


Code Snippet: 

copy and paste the following code in your class.
--------------------------------------------------------------------------------------------------------


   public class PaginatedList<T> : List<T>

    {

        public int PageIndex { get; private set; }

        public int TotalPages { get; private set; }


        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);

            this.AddRange(items);
        }

        public bool HasPreviousPage
        {
            get
            {
                return (PageIndex > 1);
            }
        }

        public bool HasNextPage
        {
            get
            {
                return (PageIndex < TotalPages);
            }
        }

        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }
    }
--------------------------------------------------------------------------------------------------------


Step# 3:  


Copy and the paste this below code in place of old index action method, a new input parameter of page number is added which will hold the page reference.
--------------------------------------------------------------------------------------------------------


    [HttpGet]

        public async Task<IActionResult> Index(string sortOrder, string searchString, string currentFilter, int? pageNumber)

        {



            ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
            if (searchString != null)
            {
                pageNumber = 1;
            }
            else
            {
                searchString = currentFilter;
            }
            ViewData["CurrentFilter"] = searchString;


            var li = from s in db.TblUser
                     select s;

            if (!String.IsNullOrEmpty(searchString))
            {
                li = li.Where(s => s.UUserName.Contains(searchString)
                                       || s.UEmail.Contains(searchString));
            }

            switch (sortOrder)
            {
                case "name_desc":
                    li = li.OrderByDescending(s => s.UUserName);
                    break;
                case "Date":
                    li = li.OrderBy(s => s.UAddedDate);
                    break;
                case "date_desc":
                    li = li.OrderByDescending(s => s.UAddedDate);
                    break;
                default:
                    li = li.OrderBy(s => s.UUserName);
                    break;
            }

            int pageSize = 3;
            return View(await PaginatedList<TblUser>.CreateAsync(li.AsNoTracking(), pageNumber ?? 1, pageSize));
            //  return View(await li.AsNoTracking().ToListAsync());
        }
--------------------------------------------------------------------------------------------------------

Step# 4:  


Go to the view page of this action method . just right click on Index method and select go to view and paste the below html code : 
------------------------------------------------------------------------------------------

@model PaginatedList<WebApplication7.Models.TblUser>
@{
    ViewData["Title"] = "Index";
}
    <div style="border:1px solid black;box-shadow:13px 9px 32px 2px blanchedalmond;padding:10px;">

        <a asp-action="Create" class="btn btn-primary btn-block">Create New</a>
        <form asp-action="Index" method="get">
            <div class="form-actions no-color">
                <p style="margin-top:20px">
                    <input type="text" name="SearchString" value="@ViewData["currentFilter"]" />
                    <input type="submit" value="Search" class="btn btn-outline-success btn-sm" /> |
                    <a asp-action="Index">Back to Full List</a>
                </p>
            </div>
        </form>

        @if (Model == null)
        {
            <h1 style="color:red;text-align:center">No data Found</h1>

        }
        else
        {
            <table class="table table-responsive">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Image</th>
                        <th>
                            <a asp-action="Index" asp-route-sortOrder="@ViewData["NameSortParm"]"> <span class="glyphicon glyphicon-sort"> Name</span>  </a>

                        </th>
                        <th>Email</th>
                        <th>
                            <a asp-action="Index" asp-route-sortOrder="@ViewData["DateSortParm"]"> <span class="glyphicon glyphicon-sort"> Added Date</span>  </a>


                        </th>
                        <th>Is Login</th>
                        <th>Is Approved</th>
                        <th>Details</th>
                    </tr>
                </thead>

                <tbody>

                    @foreach (var item in Model)
                    {
                        <tr>
                            <td>@item.UId</td>
                            <td><img src="~/img/@item.UProfilePicture" style="height:70px;width:70px;" /></td>
                            <td>@item.UUserName</td>
                            <td>@item.UEmail</td>
                            <td>@item.UAddedDate</td>
                            <td>@item.UIsuserlogin</td>
                            <td>@item.UIsuseraproved</td>
                            <td>
                                <a asp-action="Details" asp-route-id="@item.UId">Details</a>

                            </td>
                        </tr>
                    }
                </tbody>

            </table>

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

        <a asp-action="Index"
           asp-route-sortOrder="@ViewData["CurrentSort"]"
           asp-route-pageNumber="@(Model.PageIndex - 1)"
           asp-route-currentFilter="@ViewData["CurrentFilter"]"
           class="btn btn-default @prevDisabled">
            Previous
        </a>
        <a asp-action="Index"
           asp-route-sortOrder="@ViewData["CurrentSort"]"
           asp-route-pageNumber="@(Model.PageIndex + 1)"
           asp-route-currentFilter="@ViewData["CurrentFilter"]"
           class="btn btn-default @nextDisabled">
            Next
        </a>
    </div>

------------------------------------------------------------------------------------------
The highlighted lines represents the changes which I made in view to apply Pagination.





Conclusion : There you go to use pagination  on your view page. Thank you for reading ,Have a good day ! In the next article we will learn to apply create or add new records  in asp.net core.

Reference : 

https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-3.0


Previous Lesson                                                                                                Next Lesson

1 Comments:

At October 11, 2019 at 2:10 PM , Blogger Developer mind said...

very easy and helpful blog

 

Post a Comment

Do not Add Spam links in the Comment Box

Subscribe to Post Comments [Atom]

<< Home