返回
软件
分类

3、把3个ashx文件简化为1个,简单介绍如下

日期: 2020-02-15 21:15 浏览次数 : 200

aspx 页面:

先看效果图:
必赢备用网址 1

参考了:

复制代码 代码如下:

实现原理很简单,使用了jquery.pagination这个插件,每当点击页码时异步去服务器去取该页的数据,简单介绍如下:
一、数据库表结构:很简单  就四个字段 分别是News_id  News_title  News_time  News_readtimes

改进的地方:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SqlPage.aspx.cs" Inherits="SqlPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";
<html xmlns=";
<head runat="server">
<title></title>
<link href="css/pagination.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server" >
<div>
<table id="tblData" width="80%" cellpadding="1" cellspacing="1" bgcolor="gray" style="text-align:center">
<tr>
<td>
NewsID
</td>
<td>
Title
</td>
<td>
SmallClassName
</td>
<td>
Author
</td>
<td>
UpdateTime
</td>
</tr>
</table>
<div id="Pagination">
</div>
</div>
</form>
</body>
</html>
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/jquery.pagination.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
var pageIndex =0; //页索引
var pageSize =20; //每页显示的条数
$(function() {
Init(0);
$("#Pagination").pagination(<%=pageCount %>, {
callback: PageCallback,
prev_text: '上一页',
next_text: '下一页',
items_per_page: pageSize,
num_display_entries: 5,
current_page: pageIndex,
num_edge_entries: 1
});
function PageCallback(index, jq) {
Init(index);
}
});
function Init(pageIndex) {
$.ajax({
type: "POST",
dataType: "text",
url: 'SqlPage.aspx',
data: "pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize,
success: function(data) {
if(data!=""){
$("#tblData tr:gt(0)").remove();//移除所有的数据行
data=$.parseJSON(data);
$.each(data.News,function(index,news){
$("#tblData").append("<tr bgcolor='white'><td>"+news.NewsID+"</td><td algin='left'>"+news.Title+"</td><td>"+news.SmallClassName+"</td><td>"+news.Author+"</td><td>"+news.Updatetime+"</td></tr>"); //将返回的数据追加到表格
});
}
}
});
}
</script>

二、前台页面代码:

1、ashx返回json数据,减少传输数据量,html页面样式控制也比较灵活;

必赢备用网址 ,cs代码:

复制代码 代码如下:

2、改写html页的jQuery代码;

复制代码 代码如下:

<head runat="server">
    <title>JQuery无刷新分页</title>
    <link href="Styles/common.css" rel="stylesheet" type="text/css" />
    <link href="Styles/paging.css" rel="stylesheet" type="text/css" />
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.pagination.js" type="text/javascript"></script>
    <script type="text/javascript">   
    var pageIndex = 0;
    var pageSize = 3;

3、把3个ashx文件简化为1个。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class SqlPage : System.Web.UI.Page
{
public int pageCount = 0;
public static string connString = "server=192.168.1.91;database=ReportDB;uid=sa;pwd=123456";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
pageCount = GetTotalPage();
if (Request["pageIndex"] != null && Request["pageSize"] != null)
{
int pageSize = Convert.ToInt32(Request["pageSize"]) == 0 ? 1 : Convert.ToInt32(Request["pageSize"]);
int pageIndex = Convert.ToInt32(Request["pageIndex"]) == 0 ? 1 : Convert.ToInt32(Request["pageIndex"]);
Response.Write(GetOnePage(pageSize, pageIndex));
Response.End();
}
}
}
public int GetTotalPage()
{
DBHelper.connString = connString;
string sql = "select count(*) from News";
int rs = Convert.ToInt32(DBHelper.ExecuteScalar(sql));
return rs;
}
public string GetOnePage(int pageSize, int pageIndex)
{
DBHelper.connString = connString;
string sql = string.Empty;
sql = "SELECT TOP " + pageSize + " NewsID,Title,SmallClassName,Author,Updatetime FROM News WHERE NewsID NOT IN (SELECT TOP " + pageSize * (pageIndex - 1) + " NewsID FROM News ORDER BY NewsID DESC) ORDER BY NewsID DESC";
DataTable dt = DBHelper.QueryBySql(sql);
return ConvertJson.ToJson(dt, "News");
}
}

    $(function() {      
        InitTable(0);             

一、创建表的测试数据:

        $("#Pagination").pagination(<%=pageCount %>, {
            callback: PageCallback,
            prev_text: '上一页',
            next_text: '下一页',
            items_per_page: pageSize,
            num_display_entries: 6,//连续分页主体部分分页条目数
            current_page: pageIndex,//当前页索引
            num_edge_entries: 2//两侧首尾分页条目数
        });

create table test(id int identity,title varchar(36))
declare @index int;
set @index = 1;
while(@index < 8888)
begin
    insert test(title) values (newid())
    set @index = @index + 1
end

        //翻页调用
        function PageCallback(index, jq) {          
            InitTable(index);
        }

二、.html页

        //请求数据
        function InitTable(pageIndex) {                               
            $.ajax({
                type: "POST",
                dataType: "text",
                url: 'Ajax/PagerHandler.ashx',
                data: "pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize,
                success: function(data) {                                
                    $("#Result tr:gt(0)").remove();//移除Id为Result的表格里的行,从第二行开始(这里根据页面布局不同页变)
                    $("#Result").append(data);//将返回的数据追加到表格
                }
            });           
        }
    });
    </script>
</head>

<html xmlns="" >
<head runat="server"> 
    <title></title>
     <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
     <script type="text/javascript">
         $(function() {
             Init();
         });
         function Init() {
             $("#Content").html("");
             $("#pageIndex").val(0);
             $("#pageInfo").append("当前第1页");
             $.getJSON("Handler.ashx", { type: 'first' }, function(data) {
                 $("#Content").append("<tr><th style='width:130px'>id</th><th style='width:150px'>title</th></tr>");
                 $.each(data, function(i) {
                     $("#Content").append("<tr><td>" + data[i].id + "</td><td>" + data[i].title + "</td></tr>");
                 })
             })
         }        
         function Pre() {         
             var currIndex = Number($("#pageIndex").val()) - 1;            
             Go('pre', currIndex);
         }
         function Next() {
             var currIndex = Number($("#pageIndex").val()) + 1;
             Go('next', currIndex);
         }
         function Go(type, index) {
             $("#Content").html("");
             $("#pageInfo").html("");
             if (index == 0 || index == -1) { Init(); return; }
             $.getJSON("Handler.ashx", { type: type, index: index }, function(data) {
                 $("#Content").append("<tr><th style='width:130px'>id</th><th style='width:150px'>title</th></tr>");
                 $.each(data, function(i) {
                     $("#Content").append("<tr><td>" + data[i].id + "</td><td>" + data[i].title + "</td></tr>");
                 })
                 $("#pageInfo").append("当前第 " + (index + 1) + " 页");
                 $("#pageIndex").val(index);
             });
         }
     </script>
</head>
<body>
    <form id="form1" runat="server">      
3、把3个ashx文件简化为1个,简单介绍如下。        <div style="width: 100%">
           <table id="Content" >                          
           </table>
        </div>
        <div id="PagePanel" style="margin-left:20px">
            <label id="pageInfo"></label>          
            <a href="#" onclick="Pre()">上一页</a>   
            <a href="#" onclick="Next()">下一页</a>
        </div>
        <input type="hidden" value="0" id="pageIndex" />
    </form>
</body>
</html>

复制代码 代码如下:

三、.ashx页

<form id="form1" runat="server">
    <center>
        <table id="Result" border="1" cellpadding="5" style="border-collapse: collapse; margin:20px;
            border: solid 1px #85A8BE;width:60%">
            <tr>
                <th style="width: 10%">
                    ID
                </th>
                <th style="width: 60%">
                    标题
                </th>
                <th style="width: 20%">
                    更新时间
                </th>
                <th style="width: 10%">
                    点击量
                </th>
            </tr>
        </table>
        <div id="Pagination" class="paging">
        </div>
    </center>
    </form>

public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            StringBuilder tb = new StringBuilder();
            DataBase db = new DataBase();
            int pageSize = 10;
            int pageIndex = 0;

三、页面后台文件

            string type = context.Request.Params["type"];
            switch (type)
            {               
                case "first":
                    DataTable dt1 = db.GetDataSet("select top 10 * from test", null).Tables[0];
                    tb.Append(Common.DataTableToJSON(dt1, true)); //DataTable转为JSON
                    break;
                case "next":                   
                    pageIndex = Convert.ToInt32(context.Request.Params["index"]);
                    DataTable dt2 = db.GetDataSet("select top " + pageSize.ToString() + " * from test where id> (select max(id) from (select top " + (pageSize * pageIndex).ToString() + " id from test) t)", null).Tables[0];
                    tb.Append(Common.DataTableToJSON(dt2, true));
                    break;
                case "pre":                   
                    pageIndex = Convert.ToInt32(context.Request.Params["index"]);
                    DataTable dt3 = db.GetDataSet("select top " + pageSize.ToString() + " * from test where id> (select max(id) from (select top " + (pageSize * pageIndex).ToString() + " id from test) t)", null).Tables[0];
                    tb.Append(JSONHelper.DataTableToJSON(dt));
                    break;
            }

这里主要是获取记录总数:

            context.Response.Write(tb.ToString());
        }

复制代码 代码如下:

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

public string pageCount = string.Empty;//总条目数

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                pageCount = new News().GetNewsCount();
            }
        }

四、效果

四、最主要的是ajax处理程序:PagerHandler.ashx

id title
11 12937A34-8EFA-4703-946A-FDE12BC3F5AB
12 DAF9D2AC-3BEE-4BF6-955A-CA57EC2D1281
13 F9DB3478-AE84-42AB-9A49-F02363EEECE8
14 5E67126F-20B8-40BF-9E38-A45665E2B247
15 6F25D12F-CF24-43B0-A1A6-ED917B8466C8
16 9464242D-B0C6-407C-8779-4C15BD64E474
17 AB7A7DB3-A117-41B4-8EF2-00F01ACF1058
18 9A332F56-9C23-45B1-B49B-4E62095870ED
19 829D803D-5288-4B71-AB35-3C6A32352F29
20 307E8ABA-D975-4F01-AC4F-25F50A4CA52A

复制代码 代码如下:

当前第 2 页 上一页     下一页

 public class PagerHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string str = string.Empty;
            int pageIndex = Convert.ToInt32(context.Request["pageIndex"]);
            int size = Convert.ToInt32(context.Request["pageSize"]);
            if (pageIndex == 0)
            {
                pageIndex = 1;
            }
            int count = 0;


            News n = new News();
            List<News> list = n.GetNewsList(pageIndex, size, ref count);
            StringBuilder sb = new StringBuilder();
            foreach (News p in list)
            {
                sb.Append("<tr><td>");
                sb.Append(p.News_id);
                sb.Append("</td><td>");
                sb.Append("<a href='#'>"+p.News_title+"</a>");
                sb.Append("</td><td>");
                sb.Append(p.News_time);
                sb.Append("</td><td>");
                sb.Append(p.News_readtimes);
                sb.Append("</td></tr>");
            }
            str = sb.ToString();
            context.Response.Write(str);
        }

备注 (2010-7-10)

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

用sql2005 row_number()分页方法,.ashx页面代码可简化为

实现原理很简单,使用了jquery.pagination这个插件,每当点击页码时异步去服务器去取该页的数据,简单介绍如下: 一、数据库...

 public class Handler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
           
            DataBase db = new DataBase();
            int pageSize = 10;
            int pageIndex = 0;
            int.TryParse(context.Request.Params["index"], out pageIndex);
            string type = context.Request.Params["type"];
           
            string sql = string.Format("select * from ( select row_number() over (order by id) as rowNum,* from test) as t "
                + " where rowNum>{0} and rowNum<={1}", pageIndex * pageSize, (pageIndex+1) * pageSize);

            DataTable dt = db.GetDataSet(sql, null).Tables[0];    

            context.Response.Write(JSONHelper.DataTableToJSON(dt));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

备注:

其中JSONHelper.DataTableToJSON(dt)方法为DataTable解析成JSON,见另一篇文章JSONHelper 帮助类