程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> 一步步打造漂亮的新聞列表(無刷新分頁、內容預覽)第三章

一步步打造漂亮的新聞列表(無刷新分頁、內容預覽)第三章

編輯:ASP.NET基礎
我們來看一下需求分析:

3.==》無刷新的分頁讀取新聞列表,在點擊下一頁的時候觸發事件,調用ajax去數據庫中查找下一頁的數據並返回,然後顯示在頁面上。

這裡面有兩個事件,都是js事件,我們用jquery代碼來實現。

分頁的話,我們采用jquery的分頁插件pagination,官方地址為http://plugins.jquery.com/project/pagination下載js文件和css文件(最下面附下載地址)

先講講它的基本用法:

跟一般的jQuery插件一樣,此插件使用也很簡單便捷。方法是pagination,例如$("#page").pagination(100);,這裡的100參數是必須的,表示顯示項目的總個數,這是最簡單的使用。

例如下面的使用代碼:
復制代碼 代碼如下:
$("#Pagination").pagination(56, {
num_edge_entries: 2,
num_display_entries: 4,
callback: pageselectCallback,
items_per_page:1
});

這段代碼表示的含義是:總共有56(maxentries)個列表項,首尾兩側分頁顯示2(num_edge_entries)個,連續分頁主體數目顯示4(num_display_entries)個,回調函數為pageselectCallback(callback),每頁顯示的列表項為 1(items_per_page)。您可以對照參數表修改配置這裡的參數。

具體的用法可以參考官方文檔或是http://www.cnblogs.com/aosiyelong/archive/2010/03/30/1700262.html

然後講講如何將它整合到我們這邊來。

在NewsList.aspx頁面中添加相關的js文件和css文件(最下面附下載地址):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>

然後,我們來看關鍵的js代碼:
復制代碼 代碼如下:
<script type="text/javascript" language="javascript">
$().ready(function() {
InitData(0);
});
//處理翻頁
function pageselectCallback(page_id, jq) {
//alert(page_id);
InitData(page_id);
};
function InitData(pageindx)
{
var tbody = "";
var orderby="news_id";
$.ajax({
type: "POST",//用POST方式傳輸
dataType:"json",//數據格式JSON
url:'Ajax/NewsHandler.ashx',//目標地址
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);
//奇偶行顏色不同
$("#productTable tr:gt(0):odd").attr("class", "odd");
$("#productTable tr:gt(0):even").attr("class", "enen");

}
});
$("#pagination").pagination(<%=pagecount %>, {
callback: pageselectCallback,
prev_text: '<< 上一頁,
next_text: '下一頁 >>',
items_per_page:9,
num_display_entries:6,
current_page:pageindx,
num_edge_entries:2
});
}
</script>

這裡有必要說明下json數據格式,JSON(JavaScript Object Notation) 是一種輕量級的數據交換格式,它是類似於xml的數據交換格式,格式示例如下:
復制代碼 代碼如下:
[
{
"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有現成的josn處理的dll,名為Newtonsoft.Json.Net20(最下面附下載地址),用它處理json非常的方便,我們可以像處理對象一樣處理json。
因為我們在讀取列表的時候從數據庫中讀出來的是一張table(datatable格式),而要將它顯示在前台,如果自己一個個拼湊字符串的話會非常麻煩,而且擴展性不好,所有我們采用json文件,這樣就需要一個方法將datatable轉為json,該方法如下:
代碼
復制代碼 代碼如下:
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)是用來處理第pageindx頁的顯示數據的,我們著重來看一下這個ajax處理文件NewsHandler.ashx,當然也可以用aspx文件作為ajax後台處理文件。

在項目中添加ajax文件夾用來存放ajax處理文件,並且添加Generic Handler類型的文件(或是一般的webform),取名為NewsHandler.ashx,這個文件是用來處理ajax請求的。

主要代碼如下:
復制代碼 代碼如下:
int pageindex;//頁數
int.TryParse(context.Request["pageno"], out pageindex);//把賦值給pageindex
string orderby = context.Request["orderby"].ToString();//以什麼排序
DataTable dt = new DataTable();
dt = PageData(pageindex, 10, "tb_news", orderby);//獲取數據
string jsonData = DataTableToJSON(dt, "News");//創建json對象,將datatable對象轉換為json對象
context.Response.Write(jsonData);//返回json數據

上面的代碼中有這樣一個方法 PageData(pageindex, 10, "tb_news", orderby);方法主要獲取第幾頁的數據,詳細代碼如下:
代碼
復制代碼 代碼如下:
#region 返回特定頁數的數據
/// <summary>
/// 返回特定頁數的數據
/// </summary>
/// <param name="pageindex">特定的頁數</param>
/// <param name="pagesize">頁的大小</param>
/// <param name="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());//數據的總數
int pageCount;//總共的頁數
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


整合一下就實現了需求分析的第三點了。可能上面的代碼有點多有點亂。
按照以下的步驟:
1。將相應的js文件和css文件拷到對應的位置
2。添加ajax文件,並添加NewsHandler.ashx文件用以處理ajax請求
3。在NewsHandler.ashx.cs文件中添加代碼,有兩個方法比較重要,PageData(int pageindex, int pagesize, string table, string orderby)和DataTableToJSON(DataTable dt, string dtName)
4。將NewsHandler.ashx.cs中處理代碼和返回的json字符串整合好,主要代碼以在上文給出,在這裡注意添加命名空間和添加引用(提供下載)
5。編輯NewsList.aspx文件,分別編輯前台和後台。前台用以顯示(已大體給出,需結合上一篇文章),後台主要得到一個新聞條數
主要代碼如下:
復制代碼 代碼如下:
protected void InitPageCount()
{
conn = new OleDbConnection(connectionString);//創建新的連接
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);//如果連接失敗,將錯誤顯示出來
}
finally
{
conn.Close();//一定要及時關掉conn
}
}

需-需聲明protected string pagecount;以便讓前台能夠獲取
附代碼的下載:(只實現了無刷新的分頁,預覽新聞內容等待下一章)

css、js、dll、項目(僅無刷新分頁)

注:雖然提供了完整的代碼,但不建議一開始就下載完整的,要自己動手
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved