Step by step to create a beautiful news list of no refresh pagination content preview chapter 3

  • 2020-05-10 17:56:29
  • OfStack

Let's look at 1 demand analysis:

3.==) read the news list in a page without any refresh. When the next page is clicked, the event will be triggered.

There are two events, both of which are js events, which we implement with jquery code.

Paging, we adopt jquery paging plugin pagination, is the official address http: / / plugins jquery. com/project/js pagination download files and css file download address attached below the (most)

First, the basic usage:

Like the 1-like jQuery plugin 1, this plugin is also easy to use. The method is pagination, such as $("#page").pagination(100); , where the 100 parameter is required, represents the total number of items to display, which is the easiest to use.

For example, the following usage code:
 
$("#Pagination").pagination(56, { 
num_edge_entries: 2, 
num_display_entries: 4, 
callback: pageselectCallback, 
items_per_page:1 
}); 

This code indicates that there are altogether 56(maxentries) list items, 2(num_edge_entries) list items, 4(num_display_entries) number of consecutive page subjects, pageselectCallback(callback) callback function, and 1(items_per_page) list items per page. You can modify the configuration parameters here against the parameters table.

Specific usage can refer to the official documentation or http: / / www cnblogs. com aosiyelong/archive 2010/03/30/1700262. html

And then we'll talk about how we can integrate that into our side.

On the NewsList.aspx page, add the relevant js file and css file (bottom with download address) : jquery-1.4.1.js, pagination.js
 
<link type="text/css" rel="Stylesheet" href="css/newsList.css" /> 
<link type="text/css" rel="Stylesheet" href="css/pagination.css" /> 
<script src="js/jquery-1.4.1.js" type="text/javascript"></script> 
<script src="js/jquery.pagination.js" type="text/javascript"></script> 

Then, let's look at the key js code:
 
<script type="text/javascript" language="javascript"> 
$().ready(function() { 
InitData(0); 
}); 
// Processing page  
function pageselectCallback(page_id, jq) { 
//alert(page_id); 
InitData(page_id); 
}; 
function InitData(pageindx) 
{ 
var tbody = ""; 
var orderby="news_id"; 
$.ajax({ 
type: "POST",// with POST Way to transport  
dataType:"json",// The data format JSON 
url:'Ajax/NewsHandler.ashx',// The target address  
data:"pageno="+(pageindx+1)+"&orderby="+orderby, 
success:function(json) { 
$("#productTable tr:gt(0)").remove(); 
var productData = json.News; 
$.each(productData, function(i, n) { 
var trs = ""; 
trs += "<tr><td style='text-align:center'><a href=\"NewsRead.aspx?news_id="+n.news_id+"\" class=\"info2\" >" + n.news_title + "</a></td><td style='text-align:center'>" + n.news_readtimes + "</td><td style='text-align:center'>" + n.news_time + "</td></tr>"; 
tbody += trs; 
}); 
$("#productTable").append(tbody); 
// The odd and even rows are different colors  
$("#productTable tr:gt(0):odd").attr("class", "odd"); 
$("#productTable tr:gt(0):even").attr("class", "enen"); 

} 
}); 
$("#pagination").pagination(<%=pagecount %>, { 
callback: pageselectCallback, 
prev_text: '<<  on 1 page , 
next_text: ' Under the 1 page  >>', 
items_per_page:9, 
num_display_entries:6, 
current_page:pageindx, 
num_edge_entries:2 
}); 
} 
</script> 

It is necessary to note here that json data format, JSON(JavaScript Object Notation) is a lightweight data exchange format, which is similar to xml data exchange format. An example of the format is as follows:
 
[ 
{ 
"term":"BACCHUS", 
"part":"n.", 
"definition":"A convenient deity invented by the ancients as an excuse for getting drunk.", 
"quote":[ 
"Is public worship,then,a sin.", 
"That for devotions paid to Bacchus", 
"The lictors dare to run us in.", 
"And resolutely thump and whack us?" 
], 
"author":"Jorace" 
}, 
{ 
"term":"BACKBITE", 
"part":"v.t.", 
"definition":"To speak of a man as you find him when he can t find you." 
}, 
{ 
"term":"BEARD", 
"part":"n.", 
"definition":"The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the bead." 
} 
] 

asp.net has a ready-made dll processed by josn, called Newtonsoft.Json.Net20 (the download address is attached at the bottom), which is very convenient for processing json. We can process json like object 1.
Because what we read from the database when reading the list is a piece of table (datatable format), and to display it in the foreground, it would be very troublesome to piece together all the strings by ourselves, and the expansibility is not good. So we use json file, so we need a method to convert datatable to json, which is as follows:
code
 
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(); 
} 



js: InitData(pageindx) is used to process the display data on pageindx page. Let's focus on ajax NewsHandler.ashx. Of course, aspx can also be used as ajax background processing file.

Add the ajax folder to the project to hold the ajax processing files, and add the Generic Handler type file (or 1-like webform) named NewsHandler.ashx to handle the ajax requests.

The main code is as follows:
 
int pageindex;// Number of pages  
int.TryParse(context.Request["pageno"], out pageindex);// Assigned to pageindex 
string orderby = context.Request["orderby"].ToString();// In what order  
DataTable dt = new DataTable(); 
dt = PageData(pageindex, 10, "tb_news", orderby);// To get the data  
string jsonData = DataTableToJSON(dt, "News");// create json object , will datatable Object conversion to json object  
context.Response.Write(jsonData);// return json data  

The code above has a method PageData(pageindex, 10, "tb_news", orderby); The method mainly obtains the data of the page. The detailed code is as follows:
code
 
#region  Returns data for a specific number of pages  
/// <summary> 
///  Returns data for a specific number of pages  
/// </summary> 
/// <param name="pageindex"> Specific number of pages </param> 
/// <param name="pagesize"> The size of the page </param> 
/// <param name="table"> Which table </param> 
/// <returns></returns> 
public DataTable PageData(int pageindex, int pagesize, string table, string orderby) 
{ 
string connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["NewsConnection"].ToString(); 
OleDbConnection conn; 
if (pageindex < 1) 
pageindex = 1; 
conn = new OleDbConnection(connectionString); 
DataTable dt=new DataTable(); 
try 
{ 
conn.Open(); 
OleDbCommand cmdTotal = new OleDbCommand("select count(0) from " + table, conn); 
int recordCount = Convert.ToInt32(cmdTotal.ExecuteScalar());// Total number of data  
int pageCount;// Total number of pages  
if (recordCount % pagesize > 0) 
pageCount = recordCount / pagesize + 1; 
else 
pageCount = recordCount / pagesize; 
if (pageindex > pageCount) 
pageindex = pageCount; 
DataTable dataTemp = new DataTable(); 
string cmdText = "select news_id,news_title,news_readtimes,news_time from " + table + " order by " + orderby + " desc"; 
OleDbCommand cmd = new OleDbCommand(cmdText, conn); 
OleDbDataAdapter oda = new OleDbDataAdapter(cmd); 
oda.Fill(dataTemp); 
dt= dataTemp.Clone(); 
for (int i = 0; i < pagesize; i++) 
{ 
if (recordCount <= (pagesize * (pageindex - 1) + i)) 
break; 
dt.Rows.Add(dataTemp.Rows[pagesize * (pageindex - 1) + i].ItemArray); 
} 
} 
catch (Exception e) 
{ 
} 
finally 
{ 
conn.Close(); 
} 
return dt; 
} 
#endregion 


Integration 1 brings us to the third point of requirements analysis. Maybe the code above is a little bit messy.
Follow these steps:
1. Copy the corresponding js file and css file to the corresponding location
2. Add the ajax file, and add the NewsHandler.ashx file to process the ajax request
3. Adding the code to the NewsHandler.ashx.cs file is important for two methods, PageData(int pageindex, int pagesize, string table, string orderby) and DataTableToJSON(DataTable dt, string dtName)
4. Integrate the NewsHandler.ashx.cs processing code with the returned json string. The main code is given above.
5. Edit the NewsList.aspx file and edit the foreground and background, respectively. The foreground is used to display (it has been roughly given, which needs to be combined with the previous article), and the background mainly gets 1 news number
The main code is as follows:
 
protected void InitPageCount() 
{ 
conn = new OleDbConnection(connectionString);// Create a new connection  
try 
{ 
conn.Open(); 
string cmdText = "select count(0) as pages from tb_news"; 
OleDbCommand cmd = new OleDbCommand(cmdText, conn); 
DataTable dt = new DataTable(); 
OleDbDataAdapter oda = new OleDbDataAdapter(cmd); 
oda.Fill(dt); 
if (dt != null) 
{ 
pagecount = dt.Rows[0]["pages"].ToString(); 
} 

} 
catch (Exception e) 
{ 
pagecount = "0"; 
Response.Write("Error : " + e.Message);// If the connection fails, the error is displayed  
} 
finally 
{ 
conn.Close();//1 Make sure you turn it off in time conn 
} 
} 

Required - required to declare protected string pagecount; So that the front desk can get it
Download with code :(only implement non-refresh pagination, preview the news content and wait for the next chapter)

css, js, dll, project (no refresh pagination only)

Note: although the complete code is provided, it is not recommended to download the complete code at the beginning of 1. Do it yourself

Related articles: