I. Use the jquery plug-in pagination to implement Ajax without refreshing pages:
Only the main code and comments are listed below. For details, refer to the final source code:
We need to use the following files: jquery.js, jquery.pagination.js, pagination.css
And the plug-in newtonsoft. JSON. netw.dll used to convert datatable to JSON. The file is included in the bottom source file.
Paging storage process:
Set ansi_nulls ongoset quoted_identifier ongo -- ============================ ============ -- Author: yu yongbin -- create Date: -- Description: Paging. row_number () is used () -- ===================================================== ====== create procedure [DBO]. [proc_fenye] @ tblname varchar (255), -- table name @ strfields varchar (1000) = '*', -- columns to be returned. The default value is * @ strorder varchar (255) = '', -- Name of the sorted field, required @ strordertype varchar (10) = 'asc ',-- Sorting method. The default value is ASC @ pagesize Int = 10. -- page size. The default value is 10 @ pageindex Int = 1. -- page number. The default value is 1 @ strwhere varchar (1500) = ''-- Query condition (Note: Do not add where) asdeclare @ strsql varchar (5000) If @ strwhere! = ''Set @ strwhere = 'where' + @ strwhereset @ strsql = 'select * from ('+ 'select row_number () over (order by '+ @ strorder + ''+ @ strordertype +') as pos, '+ @ strfields + ''+ 'from' + @ tblname +'' + @ strwhere +') as SP where POS between '+ STR (@ PageIndex-1) * @ pagesize + 1) + 'and' + STR (@ pageindex * @ pagesize) exec (@ strsql)
Main functions of the data access layer:Retrieve paging data and calculate the total number of items (see what parameters are passed in)
/// <Summary> retrieve the data list by PAGE (all fields + class names) </Summary> /// <Param name = "order"> sorting field </param> /// <Param name = "ordertype"> sorting type: desc or ASC </param> /// <Param name = "pagesize"> page size </param> /// <Param name = "pageindex"> page index </Param> /// <Param name = "strwhere"> condition </param> /// <returns> </returns> Public dataset getlist (string order, string ordertype, int pagesize, int pageindex, string strwhere) {database DB = databasefactory. created Atabase (); dbcommand = dB. getstoredproccommand ("proc_fenye"); dB. addinparameter (dbcommand, "tblname", dbtype. ansistring, "news"); dB. addinparameter (dbcommand, "strfields", dbtype. ansistring, "*"); dB. addinparameter (dbcommand, "pagesize", dbtype. int32, pagesize); dB. addinparameter (dbcommand, "pageindex", dbtype. int32, pageindex); dB. addinparameter (dbcommand, "strorder", dbtype. string, ORD Er); dB. addinparameter (dbcommand, "strordertype", dbtype. string, ordertype); dB. addinparameter (dbcommand, "strwhere", dbtype. ansistring, strwhere); Return dB. executedataset (dbcommand );} /// <summary> calculate the number of records </Summary> /// <Param name = "strwhere"> condition </param> /// <returns> </returns> Public int calccount (string strwhere) {string SQL = "select count (1) From News"; if (! String. isnullorempty (strwhere) {SQL + = "where" + strwhere;} database DB = databasefactory. createdatabase (); dbcommand = dB. getsqlstringcommand (SQL); Return Int. parse (dB. executescalar (dbcommand ). tostring ());}
The following is the main code:
1,Introduce JS and CSS on the page
<script src="js/jquery-1.4.2.js" type="text/javascript"></script><script src="js/jquery.pagination.js" type="text/javascript"></script><link href="Css/pagination.css" rel="stylesheet" type="text/css" /><script src="js/NewsAjaxPager.js" type="text/javascript"></script>
2,Page HTML code
<! -- Content list --!> <Ul id = "pagecontain" class = "newslist"> <! -- Load image --!> <Li id = "loadimg" style = "width: 100%; Height: 60px; text-align: center; margin-top: 50px; "> </LI> <! -- The content will be dynamically output here --!> </Ul> <! -- Page number, ID cannot be changed --!> <Div id = "pagination" class = "Digg"> </div>
3,Getnewslist. ashx on the general processing page. Retrieve the paging data and the total number of items according to the conditions.
<% @ Webhandler Language = "C #" class = "getnewslist" %> using system; using system. web; using system. data; // <summary> // obtain the news list, which is used to list Ajax pages and total number of pages. /// </Summary> public class getnewslist: ihttphandler {Dal. newsdao = new Dal. newsdao (); Dal. productcategorydao catdao = new Dal. productcategorydao (); Public void processrequest (httpcontext context) {context. response. contenttype = "text/plain"; string Act Ion = context. request ["action"]; If (Action = "pager") // retrieves the paging list {// sorting field string order = context. request ["order"]. tostring (). trim (); string ordertype = context. request ["ordertype"]. tostring (). trim (); // page size string pagesizestr = context. request ["pagesize"]. tostring (). trim (); int pagesize; Int. tryparse (pagesizestr, out pagesize); If (pagesize = 0) {pagesize = 10;} // page index string pageindexstr = C Ontext. request ["pageindex"]. tostring (). trim (); int pageindex; Int. tryparse (pageindexstr, out pageindex); If (pageindex = 0) {pageindex = 1;} // extract the data datatable dt = newsdao. getlist (Order, ordertype, pagesize, pageindex, strwhere (context )). tables [0]; // converts a able to JSON string jsondate = Common. webhelper. datatabletojson (DT, "listdata"); context. response. write (jsondate);} else if (Action = "PAG Ecount ") // obtain the total number of items {context. response. write (newsdao. calccount (strwhere (context) ;}/// <summary> /// query condition /// </Summary> private string strwhere (httpcontext context) {string strwhere = "isshow = '1'"; string id = context. request ["CID"]. tostring (). trim (); If (! String. isnullorempty (ID) & Common. webhelper. isposint (ID) {catdao. getallchildcatid (ID, ref ID); strwhere + = "and categoryid in (" + ID + ")"; // ref ID} return strwhere ;} public bool isreusable {get {return false ;}}}
Function for converting able to JSON
/** Created by: Yu yongbin * Creation Time: 9:59:50 * Description: website help class (common class) * copyright: Yu yongbin */using system; using system. collections. generic; using system. text; using system. security. cryptography; using system. text. regularexpressions; using system. web; using system. web. ui; using system. web. UI. webcontrols; using system. data; using system. io; using newtonsoft. JSON; // Add the reference namespace common {// <summary> website help class </Summary> public class webhelper {// <summary> to convert datetable to JSON format data </ summary> /// <Param name = "DT"> name of the able to be converted </param> /// <Param name = "dtname"> the converted key is as follows: JSON. dtname obtains data </param> /// <returns> </returns> Public static string datatabletojson (datatable DT, string dtname) {stringbuilder sb = new stringbuilder (); stringwriter Sw = new stringwriter (SB); Using (jsonwriter JW = new jsontextwriter (SW) {jsonserializer SER = new jsonserializer (); JW. writestartobject (); JW. writepropertyname (dtname); JW. writestartarray (); foreach (datarow DR in DT. rows) {JW. writestartobject (); foreach (datacolumn DC in DT. columns) {JW. writepropertyname (DC. columnname); Ser. serialize (JW, Dr [DC]. tostring ();} JW. writeendobject ();} JW. writeendarray (); JW. writeendobject (); Sw. close (); JW. close ();} return sb. tostring ();}}}
4,★Main JS Code: (Ajax retrieves paging data, total number of lines, binds paging controls, and outputs HTML output of paging data to the foreground)
/** Yu yongbin 2011-3-22 * using jquery. pagination. JS plug-in performs Ajax paging */$ (function () {// obtain the category ID parameter (logcheck. JS) var catid = getquerystring ("CID"); // calculate the total number of pages var pagecount = 0; $. ajax ({type: "Post", cache: false, async: false, datatype: "text", URL: "handler/getnewslist. ashx ", data:" Action = pagecount & cid = "+ catid, success: function (data) {pagecount = data; // alert (pagecount );}}); // initialize data (the first page is displayed) initdata (catid, "createdate", "DESC", 20, 0, pagecount); // process flip pages, page_id is the index of the current page (0 is the first page) function pageselectcallback (page_id, JQ) {// alert (page_id); initdata (catid, "createdate", "DESC", 20, page_id, pagecount );}//★Paging main function (news category ID, sorting field, sorting type, page size, page index, total number of items) function initdata (catid, order, ordertype, pagesize, pageindx, pagecount) {// Ajax retrieves the paging list data $. ajax ({type: "Post", cache: false, datatype: "JSON", // data format: json url: "handler/getnewslist. ashx ", data: "Action = pager & cid =" + catid + "& Order =" + order + "& ordertype =" + ordertype + "& pagesize =" + pagesize + "& pageindex =" + (pageindx + 1 ), // display the loading image before sending the data, and hide B after receiving the data Eforesend: function () {$ ("# loadimg "). show (); $ ("# pagination "). hide ()}, // complete: function () {$ ("# loadimg") before sending data "). hide (); $ ("# pagination "). show ()}, // The data is received. // Ajax is successful. Success: function (JSON) {var listdate = JSON. listdata; var html = ""; $. each (listdate, function (I, n) {HTML + = "<li class = \" B \ "> <SPAN class = \" title \ "> <a href = \" newscontent. aspx? Id = "+ N. ID + "%> \" class = \ "typelink \" target = \ "_ blank \"> "+ N. longtitle + "</a> </span> <SPAN class = \" date \ ">" + N. createdate + "</span> </LI>" ;}); // output HTML $ ("# pagecontain" ).html (HTML );}}); // ajax_end // bind the pagination plug-in. The first parameter pagecount is the total number of data records $ ("# pagination "). pagination (pagecount, {callback: pageselectcallback, prev_text: '«Previous Page', next_text: 'Next page» ', items_per_page: pagesize, // number of entries displayed per page current_page: pageindx, // The index on the current page. Here 0 is the first page num_display_entries: 6, // The buttons num_edge_entries: 2 // several buttons are displayed later});} // initdata_fun_end }); // ready_end
Complete instance source code: the source code is slightly different from the one written above
Jquerypager(jquerysplit page plug-in paginationnow ajaxsplit page pai.rar
Ii. Use the aspnetpager paging control to implement paging:
Widget download and demo address: http://www.webdiyer.com/
The stored procedure and data access layer use the same code as above.
1,Add the aspnetpager control to the vs control toolbox for future call (for example, add it to the "General" column)
Click "general" → right-click "select item" → ". NET Framework component" → "Browse" → select "aspnetpager. dll" in the downloaded file"
After successful addition, the "aspnetpager" control will appear in the general toolbox.
2,REFERENCE The aspnetpager control. (The method is the same as other methods. Drag it to the specified position)
When the paging control is dragged to the page, the header is automatically added.
<% @ Register Assembly = "aspnetpager" namespace = "Wuqi. webdiyer" tagprefix = "webdiyer" %>
Page area, control code: (you can set the corresponding attribute in the property bar)
<Webdiyer: aspnetpager cssclass = "pages" currentpagebuttonclass = "CPB" id = "ANP" runat = "server" custominfohtml = "Current page % currentpageindex %/% pagecount %, % pagesize % per page, Total % recordcount % "firstpagetext =" | & lt; "lastpagetext =" & gt; | "pageindexboxtype =" textbox "pagesize =" 20 "showcustominfosection =" Left "showpageindexbox =" never "numericbuttoncount =" 5 "layouttype =" Div "custominfoclass =" pages_left "onpagechanged" anp_pagechanged "custominfosectionwidth =" 40% "urlpaging =" true "> </webdiyer: aspnetpager>
3,Display paging data
Bind data with repeater
<asp:Repeater ID="repList" runat="server"><ItemTemplate><li class="b"><span class="title"><a href="newscontent.aspx?id=<%#Eval("Id")%>" class="typelink" target="_blank"><%#Eval("LongTitle")%></a></span><span class="date"><%#Eval("CreateDate")%></span></li></ItemTemplate></asp:Repeater>
Background. CS code
Using system; using system. collections. generic; using system. LINQ; using system. web; using system. web. ui; using system. web. UI. webcontrols; public partial class newslist: system. web. UI. page {Dal. newsdao = new Dal. newsdao (); protected void page_load (Object sender, eventargs e) {If (! Ispostback) {// calculate the total number of pages (ANP. recordcount = newsdao. calccount (""); // bind list replistbind () ;}/// <summary> bind list data </Summary> private void replistbind () {// bind repeater replist. datasource = newsdao. getlist ("createdate", "DESC", ANP. pagesize, ANP. currentpageindex, ""); replist. databind ();} // pagination event protected void anp_pagechanged (Object sender, eventargs e) {replistbind ();}}
A: Before paging, you must calculate the total number of data items and assign the value toRecordcount attributes
B: SetPagesize(Page size) attributes,Currentpageindex(Current page index) attribute, passed to the function for extracting paging data
C: Set the Page Control'sOnpagechangedEvent, that is, when the page number changes, re-bind the paging data list