English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

MVC Asynchronous Pagination Code Sharing

As shown in the figure:

 

1Controller code 

//
    // GET: /AjaxUser/
    shopEntities shop = new shopEntities();
    public ActionResult Index()
    {
      return View();
    }
    public ActionResult loadjson()
    {
      int pageSize = Request["pageSize"] == null ?63; 10 : int.Parse(Request["pageSize"]);
      int pageIndex = Request["pageIndex"] == null ?63; 1 : int.Parse(Request["pageIndex"]);
      int totalCount = shop.tbl_admin.Count();
      //Provide all the data of userinfo to the front-end in JSON format
      var allorder = shop.tbl_admin.OrderBy(u=>u.id)
        .Skip(pageSize*(pageIndex-1))
        .Take(pageSize)
        .ToList();
      //Accept an object, internally serialize this object into a string using the JavaScript serialization class, and send it to the front-end
      var data = from u in allorder select new { u.id, u.realname, u.sex };
      string strNav = PageNavHelper.ShowPageNavigate(pageIndex, pageSize, totalCount);
      var result = new {Data=data, NavStr=strNav };
      return Json(result, JsonRequestBehavior.AllowGet);
    }

2Html code 

@{}}
  Layout = null;
}
<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width" />
  <title>Index</title>
  <link href="~/Content/NavPage.css" rel="stylesheet" />
  <script src="~/Scripts/jquery-1.8.2.min.js"></script>
  <script src="~/Scripts/jquery-ui-1.8.24.js"></script>
  <script src="~/Scripts/jquery.easyui.min.js"></script>
  <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
  <script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
  <script type="text/javascript">
    $(function () {
      //After the page is loaded, load the current page data from the backend
      initTable();
    });
  //Initialize table data
    function initTable(queryData) 
    {
      $.getJSON("/AjaxUser/loadjson",queryData, function (data) {
        var tb = $("#tbList");
        //First remove the old ones, then add the new ones
        $("#tbList tr[type=data]").remove();
        for (var i = 0; i < data.Data.length; i++)
        { 
          var strTr = "<tr type='data'>";
          strTr += "<td>" + data.Data[i].id + "</td>";
          strTr += "<td>" + data.Data[i].realname + "</td>";
          strTr += "<td>" + data.Data[i].sex + "</td>";
          strTr += "<td><a UId='" + data.Data[i].id + "' href='javascript:void(0)'>Modify</a>" +
            "<a UId='" + data.Data[i].ID + "' href='javascript:void(0)'>Delete</a></td>";
          strTr += "</tr>";
          tb.append(strTr);
        }
        $("#Nav").html(data.NavStr);
        //Binding the click event of the pagination tag
        $(".pageLink").click(function () {
          //Pop up the page number
          var strHref = $(this).attr("href");
          var queryStr = strHref.substr(strHref.indexOf('?') + 1);
          //alert(queryStr);
          initTable(queryStr);
          return false;
        });
      });
    }
  </script>
</head>
<body>
  <div>
    <table id="tbList">
      <tr>
        <td>id</td>
        <td>Name</td>
        <td>Gender</td>
        <td>Operation</td>
      </tr>
    </table>
    <div id="Nav" class="paginator"> 
    </div>     
  </div>
</body>
</html> 

3Pagination class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace MvcTest4.Models
{
  public class PageNavHelper
  {
    //It mainly outputs the tags of pagination hyperlinks
    //Custom pagination Helper extension
    public static string ShowPageNavigate(int currentPage, int pageSize, int totalCount)
    {
      var redirectTo = HttpContext.Current.Request.Url.AbsolutePath;
      pageSize = pageSize <= 0 ? 3 : pageSize;
      var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //Total number of pages
       var output = new StringBuilder();
      if (totalPages > 1)
      {
        //if (currentPage != 1)
        {//Process the home page connection
          output.AppendFormat("<a class='pageLink' href='{0}?pageIndex=1&pageSize={1}'>Home</a> ", redirectTo, pageSize);
        }
        if (currentPage > 1)
        {//Process the connection of the previous page
          output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1&pageSize={2}>Previous Page</a> ", redirectTo, currentPage - 1, pageSize);
        }
        else
        {
          // output.Append("<span class='pageLink'>Previous Page</span>");
        }
        output.Append(" ");
        int currint = 5;
        for (int i = 0; i <= 10; i++)
        {//Total, maximum displayed10numbers, previous5numbers, following5number
          if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages)
          {
            if (currint == i)
            {//Current page handling
              //output.Append(string.Format("[{0}]", currentPage));
              output.AppendFormat("<a class='cpb' href='{0}?pageIndex={1&pageSize={2}>3}</a> ", redirectTo, currentPage, pageSize, currentPage);
            }
            else
            {//General page handling
              output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1&pageSize={2}>3}</a> ", redirectTo, currentPage + i - currint, pageSize, currentPage + i - currint);
            }
          }
          output.Append(" ");
        }
        if (currentPage < totalPages)
        {//Handle the next page link
          output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1&pageSize={2}>Next Page</a> ", redirectTo, currentPage + 1, pageSize);
        }
        else
        {
          //output.Append("<span class='pageLink'>Next Page</span>");
        }
        output.Append(" ");
        if (currentPage != totalPages)
        {
          output.AppendFormat("<a class='pageLink' href='{0}?pageIndex={1&pageSize={2}>Last Page</a> ", redirectTo, totalPages, pageSize);
        }
        output.Append(" ");
      }
      output.AppendFormat("Page {0}", / Total {1}; currentPage, totalPages);//Whether this statistic is added or not is fine
      return output.ToString();
    }
  }
} 

4Pagination CSS 

body {
} 
.paginator {
  font: 12px Arial, Helvetica, sans-serif;
  padding: 10px 20px 10px 0;
  margin: 0px;
}
  .paginator a {
    border: solid 1px #ccc;
    color: #0063dc;
    cursor: pointer;
    text-decoration: none;
  }
    .paginator a:visited {
      padding: 1px 6px;
      border: solid 1px #ddd;
      background: #fff;
      text-decoration: none;
    }
  .paginator .cpb {
    border: 1px solid #F50;
    font-weight: 700;
    color: #F50;
    background-color: #ffeee5;
  }
  .paginator a:hover {
    border: solid 1px #F50;
    color: #f60;
    text-decoration: none;
  }
  .paginator a, .paginator a:visited, .paginator .cpb, .paginator a:hover {
    float: left;
    height: 16px;
    line-height: 16px;
    min-width: 10px;
    _width: 10px;
    margin-right: 5px;
    text-align: center;
    white-space: nowrap;
    font-size: 12px;
    font-family: Arial,SimSun;
    padding: 0 3px;
  } 

That's all for this article. I hope it will be helpful to everyone's learning and also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the network, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting. Provide relevant evidence, and once verified, this site will immediately delete the infringing content.)

You May Also Like