Monday, September 11, 2017

How to implement pagination in MVC application

In this article I am going to explain how to implement pagination in MVC application.

Description:
I am showing the employees information in foreach loop. I want to paginate the data. For pagination in MVC Pagedlist package is available. You can install this from Nuget package manager console. Run the below command:

Install-Package PagedList.Mvc

Implementation:
Model class of Employee (Employee.cs)

public partial class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public Nullable<int> Phone { get; set; }
        public Nullable<int> Salary { get; set; }
        public string Department { get; set; }
        public string ImagePath { get; set; }
        public string EmailId { get; set; }
    }


Add controller

Add an empty controller to project. Create action to fetch data from database. Don’t forget to add pagedlist namespace.

Complete code of controller

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using mvctest2017.Models;
using PagedList;
using System.IO;
using System.Text;
namespace mvc.Controllers
{
    public class EmployeeController : Controller
    {
        private DemoEntities db = new DemoEntities();

        //
        // GET: /Employee/
        public ActionResult Index(int? page)
        {
            var employee = db.Employees.OrderBy(e => e.Id);
            int pageSize = 2;
            int pageNumber = (page ?? 1);
            return View(employee.ToPagedList(pageNumber, pageSize));      
        }     
    }
}

Add view
Add view for index action.

Complete source of view (index.cshtml)

@*@model IEnumerable<mvc.Models.Employee>*@

@model PagedList.IPagedList<mvc.Models.Employee>
@using PagedList.Mvc;
@{
    ViewBag.Title = " Pagination in MVC application";
}
<style>
    table th {
        padding: 20px;
    }
    table td {
        text-align: center;
    }
</style>
<table align="center" style="margin-top: 50px; padding: 10px;">
    <tr>
        <th><input id="checkAll" type="checkbox" /></th>
        <th>
           Name
        </th>
        <th>
            Phone
        </th>
        <th>
            Salary
        </th>
        <th>
           Department
        </th>
        <th>
            Image
        </th>
        <th>
            Email
        </th>
        <th>Action</th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td><input type="checkbox" class="chkbox" value="@item.Id" /></td>
            <td>
                @if (item.Name != "")
                {
                    @Html.DisplayFor(modelItem => item.Name)
                }
                else
                {
                    <span style="color:red">-NA-</span>
                }
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Phone)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Salary)
            </td>
            <td>
                @if(item.Department != null)
                {
                     @Html.DisplayFor(modelItem => item.Department)
                }
                else
                {
                    <span style="color:red">-NA-</span>
                }
            </td>
            <td>
                @if (item.ImagePath != null)
                {
                    <img src="@Url.Content(item.ImagePath)" alt="aspmantra.com" height="100px" width="100px" />
                }
                else
                {
                    <img src="@Url.Content("~/images/image.jpg")" alt="aspmantra.com" height="100px" width="100px" />
                }
            </td>
            <td>
                @if (item.EmailId != null)
                {
                    @Html.DisplayFor(modelItem => item.EmailId)
                }
                else
                {
                   <span style="color:red">-NA-</span>
                }
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })
            </td>
        </tr>
    }

</table>
<div id='Paging' style="text-align:center">
    Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
    of @Model.PageCount

    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script>
    $(document).ready(function () {
        $("#checkAll").click(function () {
            if (this.checked) {
                $(".chkbox").prop('checked', $(this).prop('checked', true));
            }
            else {
                $('.chkbox').each(function () { this.checked = false; });
            }
        });
        $('.chkbox').on('click', function () {
            if ($('.chkbox:checked').length == $('.chkbox').length) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        });
    });
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />


No comments:

Post a Comment