Create custom paging in ASP.NET MVC

Sometimes we require to create custom paging in asp.net mvc application to do that we can use pager. Follow below steps:
1.)Go to package manager and download two packages:

2.) Go to controller and add following code.
a) Add using PagedList; in top.
b)Write your query as
    var person = (from p in personList
                          select p).ToPagedList(page, 10);

here ToPagedList method takes two parameter first one page number and second page size.

Complete code for a\controller action method is :
 List<Person> personList = new List<Person>();

        public ActionResult Index(int page = 1)
        {

            personList.Add(new Person
                {
                    Id = 1,
                    Name = "Shriniwas",
                    Age = 11
                });
            personList.Add(new Person
            {
                Id = 2,
                Name = "Ajay",
                Age = 11
            }); personList.Add(new Person
            {
                Id = 3,
                Name = "Amit",
                Age = 11
            }); personList.Add(new Person
            {
                Id = 4,
                Name = "Suresh",
                Age = 11
            }); personList.Add(new Person
            {
                Id = 5,
                Name = "Deepak",
                Age = 11
            });
            personList.Add(new Person
              {
                  Id = 9,
                  Name = "SSN"
              }); personList.Add(new Person
              {
                  Id = 9,
                  Name = "SSN"
              });

            var person = (from p in personList
                          select p).ToPagedList(page, 10);

            return View(person);
        }

3.) View page code is :
@model IPagedList<MVCWithTest.Models.Person>

<link href="~/Content/PagedList.css" rel="stylesheet" />


<div id="paging">
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }), PagedListRenderOptions.MinimalWithItemCountText)
</div>

<div id="table">
    <table class="table table-hover table-responsive">
        <tr>
            <td>Id</td>
            <td>Name</td>
            <td>Age</td><td>Age</td><td>Age</td><td>Age</td><td>Age</td><td>Age</td><td>Age</td>
        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @item.Id
                </td>
                <td>
                    @item.Name
                </td>
                <td>@item.Age</td>
            </tr>  
       
        }
    </table>
</div>
4). To give style to your page you can use PagedList.css file which will be downloaded when you download both packages.




Comments

Popular posts from this blog

Access Violation Exception