asp.net instance code using Jquery+ajax+json to implement no refresh paging

Source: Internet
Author: User
Tags foreach httpcontext json prev

  This article is mainly to asp.net in the use of Jquery+ajax+json to achieve no refresh pagination of the example code is introduced, the need for friends can come to the reference, you need to help

  Code as follows: <%@ Page language= "C #" autoeventwireup= "true" codefile= "AjaxJson.aspx.cs" inherits= "Ajaxjson"%> <! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns=" http://www.w3.org/1999/xhtml "> <head runat=" Server ">     <title>jquery +ajax+json paging </title>     <meta http-equiv= "Content-type content=" text/html; charset=gb2312 ">     <link href=" styles/tablecloth.css "rel=" stylesheet "type=" Text/css "/>   & nbsp <link href= "Styles/pagination.css" rel= "stylesheet" type= "Text/css"/>       <script type= "text /javascript "src=" Scripts/jquery-1.4.4.min.js "></script>     <script type=" Text/javascript " Src= "Scripts/jquery.pagination.js" ></script>     <script type= "Text/javascript" >     var pageIndex = 0;    //page index initial value     var pageSize = 10;    //per page display number initialization, modify the number of display bar, modify here can     $ (function () {        inittable (0);   &NB Sp;//load event, initialization of table data, page index 0 (first page)           /pagination, PageCount is the total number of entries, this is a required parameter, other parameters are optional   & nbsp     $ ("#Pagination"). Pagination (<%=pagecount%>, {            CALLBACK:PAG Ecallback             prev_text: ' prev ',      //Prev-button-text     &NB Sp       Next_text: ' next page ',      //Next page button-text             items_p Er_page:pagesize,  //display number             Num_display_entries:6,    //continuous pagination main body part Page entries             Current_page:pageindex,  //Current page index             Num_edge_entries:2        //both ends page entry number        });          //FlipPage invoke         function pagecallback (index, JQ) {            Inittable (Ind ex);        }          //Request data         function inittable (pag Eindex) {            $.ajax ({                type: "POST"                 DataType: "JSON",      ,     &NBS P     URL: ' supplyajax.aspx ',      //submit to general handler request data               Data: "type=show&random=" + math.random () + "&pageindex=" + (PageIndex + 1) + "&pagesize=" + pageSize, Submitted two parameters: PageIndex (page index), pageSize (show number)                     Error:func tion () {alert (' Error data ');  //error execution method                   SUCCESS:F Unction (data) {                     $ ("#Result tr:gt (0)"). Remove ();        //remove rows from the table with ID result, starting from the second line (here different page layouts according to page layout)               &NBS P     var json = data; Array                       var html = "";                     $.each (json.data, function (index, item) {  &N Bsp                    //Loop get data             & nbsp             var id = Item. Id;                         var name = Item. Name;                         var sex = Item. Sex;                         HTML = "<tr><td>" + ID + "</td><td>" + name + "</td><td>" + Sex + "</td></tr>";                    }                     $ ("#Result"). Append (HTML);            //append returned data to form                }   & nbsp        });        }    };      </script>    </head> <body&gt ;     <form id= "Form1" runat= "Server" >     <table id= "result" cellspacing= "0" cellpadding= "0" >         <tr>             <th>       &NBS P         number             </th>           &N Bsp <th>                 name   &NBSP         </th>             <th>         & nbsp       gender             </th>         </tr> &nbs P   </table>     <div id= "pagination" >     </div>     </form> ;/body> </html>     code is as follows: using System; Using System.Collections.Generic; Using System.Linq; Using System.Web; Using System.Text; Using System.Net; Using System.IO; Using System.Web.UI; Using System.Web.UI.WebControls;   public partial class AjaxJson:System.Web.UI.Page {    public string PageCount = string. Empty; Total number of entries       protected void Page_Load (object sender, EventArgs e)     {      &NBS P if (! IsPostBack)         {            String url = "/supplyajax.aspx"; &nbsp ;     &NBSp     String strresult = getrequestjsonstring (URL, "Type=getcount");             PageCount = strresult.tostring ();        }     {      #region background get ashx back data    ///<summary>    ///background get ashx back data    ///</summary>    ///<param name= "RelativePath" > Address & lt;/param>    ///<param name= "data" > Parameter </param>    ///<returns></returns >     public static string getrequestjsonstring (string relativepath, string data)     {  &NBS P     String requesturl = Getrequesturl (relativepath, data);           try         {            WebRequest Request = WebRequest.Create (Requesturl);             request. method = ' Get ';               STREAMREAder Jsonstream = new StreamReader (Request. GetResponse (). GetResponseStream ());             String jsonobject = Jsonstream.readtoend ();               return jsonobject;        }         catch         {            return string. Empty;        }    }       public static string Getrequesturl (String RelativePath, String data)     {        string absolutepath = HttpContext.Current.Request.Url.AbsoluteUr I         string hostnameandport = HttpContext.Current.Request.Url.Authority;         string applicationdir = HttpContext.Current.Request.ApplicationPath;         StringBuilder sbrequesturl = new StringBuilder ();         Sbrequesturl.append (absolutepath.substring 0, Absolutepath.indexOf (Hostnameandport));         sbrequesturl.append (hostnameandport);         sbrequesturl.append (Applicationdir);         sbrequesturl.append (relativepath);         if (!string. IsNullOrEmpty (data)         {            sbrequesturl.append ("?"); &NB Sp           sbrequesturl.append (data);        }         return sbrequesturl.tostring ();    }     #endregion  }   code is as follows: using System; Using System.Collections.Generic; Using System.Linq; Using System.Web; Using System.Data; Using System.Web.UI; Using System.Web.UI.WebControls; New    using System.Web.Script.Serialization; Using System.Text;     Public partial class SupplyAJAX:System.Web.UI.Page {    protected static list<student> St Udentlist = new list<student> ();   &nbsp protected static int RecordCount = 0;     protected static DataTable dt = Createdt ();     protected void Page_Load (object sender, EventArgs e)     {        switch (Req uest["type"])         {            case ' show ':       &N Bsp         #region Paging configuration                //Specific page number     &N Bsp           int pageIndex;                 Int. TryParse (request["PageIndex"], out pageIndex);                //page display number               I NT PageSize = Convert.ToInt32 (request["PageSize"]);                 if (pageIndex = 0)             &NBS P   {                &nbsp   PageIndex = 1;                                 #endregi on                  DataTable PAGEDDT = getpagedtable (dt, PageIndex, PageSize );                 list<student> List = new list<student> ();                 foreach (DataRow Dr in Pageddt.rows)         & nbsp       {                    Student C = new Student () &N Bsp                   c.id = (Int32) dr["Id"];                     c.name = dr["Name". ToString ();                     C.sex = dr["Sex"]. ToString ();                     LIst. ADD (c);                   {                s Tring JSON = new JavaScriptSerializer (). Serialize (list);//This is critical, otherwise error                  StringBuilder Builder = new StringBuilder ();                 Builder.append ("{");                 builder.append ("RecordCount": "+ RecordCount +", ");                 Builder.append ("" Data ":");                 builder.append (JSON);                 builder.append ("}");                 Response.ContentType = "Application/json";                 Response.Write (builder.tostring ());                 break;   &nbsp         case "GetCount":               Response.Write (dt. Rows.Count);                 break;             Case "add":                 break;             Case "Update":                 break;             Case "Delete":                 break;        }         Response.End ();    }       #region analog data     private static DataTable Createdt ()     {        DataTable dt = new DataTable ();         DT. Columns.Add (New DataColumn ("Id", typeof (int)) {defaultvalue = 0});         DT. Columns.Add (New DataColumn ("Name", typeof (String)) {DEFAULTVAlue = "1"});         DT. Columns.Add (New DataColumn ("Sex", typeof (String)) {defaultvalue = "man"});         for (int i = 1; I <= 1000 i++)         {        & nbsp   DT. Rows.Add (i, "John" + i.ToString (). PadLeft (4, ' 0 '));        }         RecordCount = dt. Rows.Count;         return DT;    }     #endregion        ///<summary>      ///to Datatabl e paging, start Page 1      ///</summary>      ///<param name= "DT" ></param> &nbsp ;    ///<param name= "PageIndex" ></param>      ///<param name= "PageSize" > </param>      ///<returns></returns>       public static DataTable GETPA Gedtable (DataTable dt, int PageIndex, int PageSize)       {          if (PageIndex = 0)               return DT;           DataTable NEWDT = dt. Copy ();           NEWDT. Clear ();             int rowbegin = (PageIndex-1) * PageSize;           int rowend = PageIndex * PageSize;           if (rowbegin >= dt. Rows.Count)               return NEWDT;           if (rowend > dt. Rows.Count)               rowend = dt. Rows.Count;           for (int i = Rowbegin i <= rowend-1 i++)           {&N Bsp             DataRow NEWDR = Newdt. NewRow ();               DataRow dr = dt. Rows[i];               foreach (DataColumn column In dt. Columns)               {                  Newdr[column. ColumnName] = Dr[column. ColumnName];               {              NEWDT. Rows.Add (NEWDR);           {          return NEWDT;      }        ///<summary>      ///get total pages       </summary>      ///<param name= "Sumcount" > Result set quantity </param>      ///& Lt;param name= "pageSize" > page number </param>      ///<returns></returns>     & nbsp public static int Getpagecount (int sumcount, int pageSize)       {          INT P age = Sumcount/pagesize;           if (sumcount% pageSize > 0)           {              page = page + 1;           &NB   Sp       return page;      }            public struct Student     {        public int Id;         public string Name;         public string Sex;    }  }  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.