Implementation of Pagination and Filtering in asp.net MVC

Implementation of Pagination and Filtering in asp.net MVC

Pagination divides the content into separate pages. It removes the hectic scroll down of the user to infinite. It increases the speed of loading through pagination.

Benefits of Pagination: 

  • It is easier to search within some limited number of lists
  • Infinite Scrolling is just like an endless game  

Filtering is also the main feature when you have to search something from the long list of options. You can find your desired result in a quick way.

When you did scaffolding on any model of the database your index action will like as

 


publicActionResult Index()

{

       return View();   

}


This Index method will display all the results without pagination. When you want to the pagination of your site first install NuGet Package named “PagedList.Mvc” and include a namespace “using PagedList;”. After adding these features you should change your Index method like below


publicActionResult Index(int? page)

        {

var employeeProfiles = db.EmployeeProfiles;

int pageSize = 8;

              int pageNumber = (page ?? 1);

       return View(employeeProfiles.OrderBy(i => i.Id).ToPagedList(page ?? 1, pageSize));

}


 

And the view of that method uses


@model PagedList.IPagedList<FYP_2.Models.EmployeeProfile>

And at the end of the view page add following code

  Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount

 

    @Html.PagedListPager(Model, page => Url.Action("Index",

        new { page, sortOrder = ViewBag.CurrentSort, currentFilter = ViewBag.CurrentFilter }))


 

This all code will add the Pagination feature to the particular which you added. Now heading towards filtering we add the following code


@using (Html.BeginForm())

       {

        <p>

            Find by name: @Html.TextBox("SearchString")

            <inputtype="submit"value="Search"/>

        </p>

    }


And after adding this code in the View move towards the Controller and Add new action with [HttpPost] method and the action which we uses earlier are now changed to following code


[HttpPost]

        publicActionResult Index(FormCollection form, int? page)

 {

if (!String.IsNullOrEmpty(SearchString))

                {

                    emp = emp.Where(s => s.FirstName.Contains(SearchString));

                }

                int pageSize = 8;

                int pageNumber = (page ?? 1);

   return View(emp.OrderBy(i => i.Id).ToPagedList(page ?? 1, pageSize));

 }



Comments