Hi shoaibshafiqa...,
Check this example. Now please take its reference and correct your code.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
Model
Pager
public class Pager
{
public Pager(int totalItems, int? page, int pageSize = 10)
{
if (pageSize == 0) pageSize = 10;
var totalPages = (int)Math.Ceiling((decimal)totalItems / (decimal)pageSize);
var currentPage = page != null ? (int)page : 1;
var startPage = currentPage - 5;
var endPage = currentPage + 4;
if (startPage <= 0)
{
endPage -= (startPage - 1);
startPage = 1;
}
if (endPage > totalPages)
{
endPage = totalPages;
if (endPage > 10)
{
startPage = endPage - 9;
}
}
TotalItems = totalItems;
CurrentPage = currentPage;
PageSize = pageSize;
TotalPages = totalPages;
StartPage = startPage;
EndPage = endPage;
}
public int TotalItems { get; private set; }
public int CurrentPage { get; private set; }
public int PageSize { get; private set; }
public int TotalPages { get; private set; }
public int StartPage { get; private set; }
public int EndPage { get; private set; }
}
CustomerSearchViewModel
public class CustomerSearchViewModel
{
public List<Customer> Customers { get; set; }
public string SearchTerm { get; set; }
public Pager Pager { get; set; }
}
Controller
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
CustomerSearchViewModel model = new CustomerSearchViewModel();
var totalRecords = GetCustomerCount("");
model.Customers = GetCustomers("", 1);
if (model.Customers != null)
{
model.Pager = new Pager(totalRecords, 1, 10);
return View(model);
}
else
{
return HttpNotFound();
}
}
[HttpPost]
public ActionResult Index(string search, int? pageNo)
{
CustomerSearchViewModel model = new CustomerSearchViewModel();
model.SearchTerm = search;
pageNo = pageNo.HasValue ? pageNo.Value > 0 ? pageNo.Value : 1 : 1;
var totalRecords = GetCustomerCount(search);
model.Customers = GetCustomers(search, pageNo.Value);
if (model.Customers != null)
{
model.Pager = new Pager(totalRecords, pageNo, 10);
return View(model);
}
else
{
return HttpNotFound();
}
}
public int GetCustomerCount(string search)
{
using (var context = new NorthwindEntities())
{
if (!string.IsNullOrEmpty(search))
{
return context.Customers.Where(p => p.ContactName != null
&& p.ContactName.ToLower().Contains(search.ToLower())).Count();
}
else
{
return context.Customers.Count();
}
}
}
public List<Customer> GetCustomers(string search, int pageNo)
{
int pageSize = 5;
using (var context = new NorthwindEntities())
{
if (!string.IsNullOrEmpty(search))
{
return context.Customers.Where(p => p.ContactName != null && p.ContactName.ToLower()
.Contains(search.ToLower()))
.OrderBy(x => x.CustomerID)
.Skip((pageNo - 1) * pageSize)
.Take(pageSize)
.ToList();
}
else
{
return context.Customers.OrderBy(x => x.CustomerID).Skip((pageNo - 1) * pageSize).Take(pageSize).ToList();
}
}
}
}
View
@model Pagination_JavaScript_MVC.Models.CustomerSearchViewModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<!-- Table Container-->
<div class="container">
<div id="tableCon">
</div>
<div id="actionCon"></div>
</div>
<div class="container tblData">
<div>
<!-- Searching Start-->
<form method="post" action="/Home/Index">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-search"></i></span>
<input type="text" id="Search" placeholder="Search" class="form-control" />
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<div class="row">
<div class="col-md-6">
<button class="btn btn-primary form-control" type="button" id="newBtn" data-toggle="modal" data-target="#myModal">
<span><i class="fa fa-plus"></i> New</span>
</button>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- Searchign End-->
</div>
<!-- Table Start-->
<table class="table table-striped" id="tbldata">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>Country</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
@foreach (var item in Model.Customers)
{
<tr class="Search" id="#row_@item.CustomerID">
<td>@item.ContactName</td>
<td>@item.City</td>
<td>@item.Country</td>
<td>
<button type="button" id="BtnEdit" data-id="@item.CustomerID"><span><i class="fa fa-edit"></i> Edit</span></button>
<button class="dltBtn" data-id="@item.CustomerID" onclick="ConfirmDeleteCat(@item.CustomerID)"><span><i class="fa fa-trash"></i> Delete</span></button>
</td>
</tr>
}
</tbody>
</table>
<!-- Table End-->
<!-- Pager Div Start -->
<strong>
<div>
@if (Model.Pager != null)
{
if (Model.Pager.CurrentPage > 1)
{
<button class="pageButtons" data-pageno="1">First</button>
<button class="pageButtons" data-pageno="@(Model.Pager.CurrentPage -1)">Previous</button>
}
for (var page = Model.Pager.StartPage; page <= Model.Pager.EndPage; page++)
{
string activeClass = Model.Pager.CurrentPage == page ? "active bg-info" : string.Empty;
<button class="@activeClass pageButtons" data-pageno="@page">@page</button>
}
if (Model.Pager.CurrentPage < Model.Pager.TotalPages)
{
<button class="pageButtons" data-pageno="@(Model.Pager.CurrentPage +1)">Next</button>
<button class="pageButtons" data-pageno="@Model.Pager.EndPage">Last</button>
}
}
</div>
</strong>
<!-- Pager Div End-->
</div>
<!-- Create popup Modal Start-->
<form id="createCat">
<div class="container">
<!-- The Modal -->
<div class="modal fade" id="myModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Enter New Category</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="form-group">
<input type="text" class="form-control" id="txtName" name="CategoryName" placeholder="Enter Category" />
</div>
<br />
<div class="form-group">
<label>Is Active?</label>
<input name="IsActive" type="radio" value="True" /> True
<input name="IsActive" type="radio" value="False" /> False
</div>
<br />
<div class="form-group">
<label>Is Featured?</label>
<input name="IsFeatured" type="radio" value="True" /> True
<input name="IsFeatured" type="radio" value="False" /> False
</div>
<br />
<label>Image</label>
<input id="ImageURL" name="ImageURL" type="hidden" />
<input id="imageUpload" name="imageUpload" type="file" />
<div class="thumb">
<img id="categoryImage" style="height:150px; width:250px;" />
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="SaveBtnCat" type="button" class="btn btn-primary" data-dismiss="modal">Save</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</form>
<!-- Create Popup Modal End-->
<!-- Delete Sweat Alerts Start-->
<div class="modal fade" id="DeleteModal">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Delete Category</h4>
<a href="#" class="close" data-dismiss="modal">×</a>
</div>
<!-- Modal body -->
<div class="modal-body">
<h4>Are you sure your want to Delete this Category ?</h4>
<div style="text-align:center;display:none" id="loaderDivD">
<img src="~/Content/images/LoadingRed.gif" style="height:200px; width:200px" />
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<a href="#" class="btn btn-default" data-dismiss="modal">Cancel</a>
<a href="#" class="btn btn-success" onclick="DeleteCat()">Confirm</a>
</div>
</div>
</div>
</div>
<input type="hidden" id="hiddenCatId" />
<!-- Delete Sweat ALerts End-->
<script type="text/javascript">
// For button Edit
$(function () {
$("[id*=BtnEdit]").click(function () {
var categoryId = $(this).attr('data-id');
$.ajax({
type: 'POST',
url: '/Home/Edit',
data: { id: categoryId }
}).done(function (response) {
$("#actionCon").html(response);
$("#myModalEdit").modal('show');
}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail");
});
});
});
//For Searching New method
$(document).ready(function () {
function Contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
$("#Search").keyup(function () {
var searchText = $("#Search").val().toLowerCase();
$(".Search").each(function () {
if (!Contains($(this).text().toLowerCase(), searchText)) {
$(this).hide();
}
else {
$(this).show();
}
});
});
});
//For Paginations
$(".pageButtons").click(function () {
$.ajax({
method:'POST',
url: '@Url.Action("Index","Home")',
data: {
pageNo: $(this).attr("data-pageno"),
search: '@Model.SearchTerm'
}
})
.done(function (response) {
$(".tblData").empty();
$("#tableCon").html(response);
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail");
});
});
//For New Button
$("#newBtn").click(function () {
$.ajax({
url: '/Home/Create',
})
.done(function (response) {
$("#actionCon").html(response);
//focusAction();
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail");
});
});
//SaveCat Modal
$("#SaveBtnCat").click(function () {
//debugger;
$.ajax({
type: 'POST',
url: '/Home/Create',
data: $("#createCat").serialize()
})
.done(function (response) {
// $("#tableCon").html(response);
window.location.href = "/Category/Index";
$("#myModal").html("");
$("#actionCon").html("");
//debugger;
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail");
});
});
//Image Upload For Create
$("#imageUpload").change(function () {
var element = this;
var formData = new FormData();
var totalFiles = element.files.length;
for (var i = 0; i < totalFiles; i++) {
var file = element.files[i];
formData.append("Photo", file);
}
$.ajax({
type: 'POST',
url: '/Shared/UploadImage',
dataType: 'Json',
data: formData,
contentType: false,
processData: false
})
.done(function (response) {
//debugger;
if (response.Success) {
$("#ImageURL").val(response.ImageURL);
$("#categoryImage").attr("src", response.ImageURL); //debugger;
}
})
.fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail");
});
});
//For Delete
var ConfirmDeleteCat = function (CategoryId) {
$("#hiddenCatId").val(CategoryId);
$("#DeleteModal").modal('show');
}
var DeleteCat = function () {
$("#loaderDivD").show();
var CatId = $("#hiddenCatId").val();
$.ajax({
type: "POST",
url: "/Home/DeleteCat",
data: { CategoryId: CatId },
success: function (result) {
$("#loaderDivD").hide();
$("#DeleteModal").modal("hide");
$("#row_" + CatId).remove();
window.location.href = "/Category/Index";
}
})
}
</script>
</body>
</html>
Screenshot