MVC First Next Prev Last Pager
Add Model>edmx File After…
Add Control
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GridviewPagingNew;
using System.Web.Helpers;
namespace GridviewPagingNew.Controllers
{
public class JobsController : Controller
{
private Naresh db = new Naresh();
const int pageSize = 10;
// GET:
Jobs
public ActionResult Index(int page=1)
{
//var
jobs = db.Jobs.Include(j => j.User);
//return
View(jobs.ToList());
var jobs = db.Jobs.OrderBy(p => p.Id).Skip((page - 1) *
pageSize).Take(pageSize).ToList();
ViewBag.CurrentPage = page;
ViewBag.PageSize = pageSize;
ViewBag.TotalPages = (int)Math.Ceiling((double)db.Jobs.Count() /
pageSize);
return View(jobs.ToList());
}
// GET:
Jobs/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
return View(job);
}
public JsonResult EfficientPaging(int? page)
{
int skip = page.HasValue ? page.Value - 1 : 0;
var data = db.Jobs.OrderBy(o => o.Id).Skip(skip *
10).Take(10).ToList();
var grid = new WebGrid(data);
var htmlString = grid.GetHtml(tableStyle: "webGrid",
headerStyle: "header",
footerStyle: "foot",
alternatingRowStyle: "alt",
columns:
new[] { grid.Column("Id"),
grid.Column("Title"), grid.Column("CountryId")});
//htmlAttributes: new { id = "DataTable" });
var tempData = htmlString.ToHtmlString();
return Json(new
{
Data =
htmlString.ToHtmlString(),
Count = db.Jobs.Count() / 10,
CurrentPage = skip
}, JsonRequestBehavior.AllowGet);
}
// GET:
Jobs/Create
public ActionResult Create()
{
ViewBag.UserId = new SelectList(db.Users, "Id", "Title");
return View();
}
// POST:
Jobs/Create
// To
protect from overposting attacks, please enable the specific properties you
want to bind to, for
// more
details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = Rss,IsCaterer,IsDice,IsDirect,IsCareesma,IsRezidor,IsIhg,IsIndeed,IsKempinski,IsSerco,IsTaj,IsCompanyXml")] Job job)
{
if (ModelState.IsValid)
{
db.Jobs.Add(job);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Title",
job.UserId);
return View(job);
}
// GET:
Jobs/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Title",
job.UserId);
return View(job);
}
// POST:
Jobs/Edit/5
// To
protect from overposting attacks, please enable the specific properties you
want to bind to, for
// more
details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Title,CompanyName,Salary,CountryId,JobDescription,MinExperience,MaxExperience,
,IsTaj,IsCompanyXml")] Job job)
{
if (ModelState.IsValid)
{
db.Entry(job).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "Title",
job.UserId);
return View(job);
}
// GET:
Jobs/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Job job = db.Jobs.Find(id);
if (job == null)
{
return HttpNotFound();
}
return View(job);
}
// POST:
Jobs/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Job job = db.Jobs.Find(id);
db.Jobs.Remove(job);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
.cshtml
File…
@model
IEnumerable<GridviewPagingNew.Job>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create
New", "Create")
</p>
@helper
buildLinks(int start, int end, string innerContent)
{
for (int i = start; i <= end; i++)
{
<a class="@(i == ViewBag.CurrentPage ? "current" : "")" href="@Url.Action("Index", "Jobs", new { page = i })">@(innerContent ?? i.ToString())</a>
}
}
@helper
pageLinks()
{
const int maxPages = 11;
if (ViewBag.TotalPages <= maxPages)
{
@buildLinks(1, (int)ViewBag.TotalPages, null)
return;
}
int pagesAfter = ViewBag.TotalPages - ViewBag.CurrentPage; // Number of pages after current
int pagesBefore = ViewBag.CurrentPage - 1; // Number of pages before current
if (pagesAfter <= 4)
{
@buildLinks(1, 1, null) // Show 1st page
int pageSubset = ViewBag.TotalPages - maxPages - 1 > 1 ?
ViewBag.TotalPages - maxPages - 1 : 2;
@buildLinks(pageSubset, pageSubset, "...") // Show page subset (...)
@buildLinks(ViewBag.TotalPages - maxPages + 3,
ViewBag.TotalPages, null) // Show last pages
return; // Exit
}
if (pagesBefore <= 4)
{
@buildLinks(1, maxPages - 2, null) // Show 1st pages
int pageSubset = maxPages + 2 < ViewBag.TotalPages ?
maxPages + 2 : ViewBag.TotalPages - 1;
@buildLinks(pageSubset,
pageSubset, "...") // Show page subset (...)
@buildLinks(ViewBag.TotalPages, ViewBag.TotalPages, null) // Show last page
return; // Exit
}
if (pagesAfter > 4)
{
@buildLinks(1, 1, null) // Show 1st pages
int pageSubset1 = ViewBag.CurrentPage - 7 > 1 ?
ViewBag.CurrentPage - 7 : 2;
int pageSubset2 = ViewBag.CurrentPage + 7 <
ViewBag.TotalPages ? ViewBag.CurrentPage + 7 : ViewBag.TotalPages - 1;
@buildLinks(pageSubset1, pageSubset1, pageSubset1 ==
ViewBag.CurrentPage - 4 ? null : "...") // Show 1st page subset (...)
@buildLinks(ViewBag.CurrentPage - 3, ViewBag.CurrentPage +
3, null) // Show middle pages
// Show
2nd page subset (...)
// only show
... if page is contigous to the previous one.
@buildLinks(pageSubset2, pageSubset2, pageSubset2 ==
ViewBag.CurrentPage + 4 ? null : "...")
@buildLinks(ViewBag.TotalPages, ViewBag.TotalPages, null) // Show last page
return; // Exit
}
}
<input type="hidden" id="hdnCurrentPage" />
<div id="divGrid">
<div id="divMain"></div>
<div id="divFoot" class="foot"></div>
</div>
@section
scripts{
<script type="text/javascript">
$(function () {
$.getJSON("/Jobs/EfficientPaging",null, function (d) {
// add the dynamic WebGrid to the body
$("#divMain").html(d.Data);
// create the footer
var footer =
createFooter(d.Count, d.CurrentPage);
$("#divFoot a").live("click", function (e) {
e.preventDefault();
// Manage Pagging
var PageCount = 1;
if ($(this).text() == "First") {
PageCount = 1;
}
else if ($(this).text() == "Last") {
PageCount =
d.Count;
}
else if ($(this).text() == "Next") {
if (d.Count == $("#hdnCurrentPage").val())
PageCount =
d.Count;
else
PageCount =
(parseInt($("#hdnCurrentPage").val()) + 1);
}
else if ($(this).text() == "Previous") {
if ($("#hdnCurrentPage").val()
== 1)
PageCount = 1;
else
PageCount =
(parseInt($("#hdnCurrentPage").val()) - 1);
}
else
PageCount = $(this).text();
var data = {
page: PageCount
};
// get data of current page
$.getJSON("/Jobs/EfficientPaging", data, function (html) {
// add the data to the table
$("#DataTable").remove();
$("#divMain").html(html.Data);
var footer =
createFooter(d.Count, html.CurrentPage);
});
});
});
});
function createFooter(totalPages, CurrentPage) {
var maxPagess = 10;
var rowsPerPage = 10;
var footer = "<div>";
if ((CurrentPage + 1) == 1) {
footer = footer + "First ";
footer = footer + "Previous ";
}
else {
footer = footer + "<a href=#>First</a> ";
footer = footer + "<a href=#>Previous</a> ";
}
var nn = 0;
if (CurrentPage == 0 || CurrentPage == 1 || CurrentPage == 2
|| CurrentPage == 3 || CurrentPage==4 || CurrentPage==5) {
nn = 1;
}
else {
nn = CurrentPage - 4;
}
for (var i = nn; i < (totalPages + 1) ; i++) {
if ((CurrentPage + 1) == i) {
footer = footer + "" + i + " ";
///footer = footer + " ";
$("#hdnCurrentPage").val(i);
}
else {
if ((CurrentPage + 5) >= i)
{
footer = footer
+ "<a href=#>" + i + "</a> ";
}
else {
}
//footer = footer + "<a href=#>" + i +
"</a> ";
}
}
if ((CurrentPage + 1) == totalPages) {
footer = footer + "Next ";
footer = footer + "Last ";
}
else {
footer = footer + "<a href=#>Next</a> ";
footer = footer + "<a href=#>Last</a> ";
}
footer = footer + "</div>";
$("#divFoot").empty();
$("#divFoot").html(footer);
return footer;
}
</script>