asp.net中Ajax分页实例

来源:互联网 发布:mac以太网ip地址 编辑:程序博客网 时间:2024/05/20 18:52
一 .ashx代码:using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using System.Data;using System.Web.Script.Serialization;namespace WebApplication1.Handlers{    /// <summary>    /// $codebehindclassname$ 的摘要说明    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    public class PageService : IHttpHandler    {        public void ProcessRequest(HttpContext context)        {            //context.Response.ContentType = "text/plain";            //context.Response.Write("Hello World");                   context.Response.ContentType = "text/plain";            string action = context.Request["action"];            if (action == "GetPageCount") //如果请求类型为取得总页数,则如下处理。             {                //该方法是建立在强连接DataSet内的,取得总记录数的方法                 int counts = 100;//new CommentTableAdapter().GetComentCount().Value;                int page = counts / 10; //默认每页10条数据                 if (counts % 10 != 0)                {                    page++;                }                context.Response.Write(page); //取得数据后返回给客户端。             }            else if (action == "GetPageData") //请求类型是取得某页的数据,则还会传一个页码过来             {                int pageNo = Convert.ToInt32(context.Request["PageNo"]);                //该方法是给出页数,去数据库表内取得对应页的数据                 var data = TestData(pageNo);                                      //将取得数据用json序列化后传回客户端                 context.Response.Write(Serialize(data));            }            //每页条数,和总条数!            if (action == "pageCount")            {                string data = "[{\"pageCount\":\"10\",\"counts\":\"100\"}]";                context.Response.Write(data);            }        }        public string Serialize(DataTable dt)        {            JavaScriptSerializer serializer = new JavaScriptSerializer();            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();            foreach (DataRow dr in dt.Rows)            {                Dictionary<string, object> result = new Dictionary<string, object>();                foreach (DataColumn dc in dt.Columns)                {                    result.Add(dc.ColumnName, dr[dc].ToString());                }                list.Add(result);            }            return serializer.Serialize(list); ;        }        public DataTable TestData(int pageNo)        {            DataTable dt = new DataTable("user");            dt.Columns.Add("name", typeof(string));            dt.Columns.Add("Comment", typeof(string));            if (pageNo > 0)            { }            else            { pageNo = 1; }            for (int i = 0; i <  5; i++)            {                DataRow dr = dt.NewRow();                dr["name"] = "name" + (i*pageNo).ToString();                dr["Comment"] = (i*pageNo).ToString();                dt.Rows.Add(dr);            }            return dt;        }        public bool IsReusable        {            get            {                return false;            }        }    }}二 .aspx代码:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxPager.aspx.cs" Inherits="WebApplication1.AjaxPager" %><!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" ><script src="js/jquery-1.4.2.min.js" type="text/javascript"></script><head runat="server">    <title></title>    <style type="text/css">        #goNum        {            width: 39px;        }    </style></head><body>    <form id="form1" runat="server">    <div>    <script type="text/javascript">    var pNum = 1;    $(function() {        //-----------------------------------------------------------         function getPageData(pageNo) { //取得某页数据的方法             $.post("Handlers/PageService.ashx", { "action": "GetPageData", "PageNo": pageNo }, function(data, status) {                if (status == "success") {                    $("#Comment").empty();                    var comments = $.parseJSON(data); //反序列化json数据。                     for (var i = 0; i < comments.length; i++) {                        var row = comments[i];                        var li = $("<li>" + row.name + " : " + row.Comment + "</li>");                        $("#Comment").append(li); //每取出一条数据就创建一个li并append到Comment/ul内。                     }                }            });        }        //获得json数据3中方法:1.$.ajax 2 $.post(此方法还的反序列化)3. getJson-------------------------------------------------------------------        getPageData(1); //        $("#pNum").html("1");        //               $.ajax({        //                   type: 'GET',   //获得数据的方式 get 和post        //                   url: 'Handlers/PageService.ashx?action=pageCount',  //url地址也可以是txt文本        //                   dataType: 'json',   //数据类型 text 、json等        //                  // data: 'action=pageCount',  //传递的参数 最后呈现效果 JsonHandler.ashx?type='';        //                   success: function(msg) {        //                       $.each(msg, function(i, n) { $("#pageCount").html(n["pageCount"]); $("#counts").html(n["counts"]); });        //                   },  //成功时的处理        //                   error: function(data) { alert(data); }  //失败时的处理        //               })        $.post("Handlers/PageService.ashx?action=pageCount", function(data, status) { if (status == "success") { var comments = $.parseJSON(data); $("#pageCount").html(comments[0].pageCount); $("#counts").html(comments[0].counts); } });        //  $.getJSON("Handlers/PageService.ashx?action=pageCount", function(data) { $.each(data, function(i, da) { $("#pageCount").html(da["pageCount"]); $("#counts").html(da["counts"]); }); });        //----------------------------------------------------------------/         //取得所有的页数并且初始化分页按钮         $.post("Handlers/PageService.ashx", { "action": "GetPageCount" }, function(data, status) {            if (status == "success") {                var pageNo = parseInt(data);                //上一页---------------------------------------------------------------                $("#prev").click(function() { //页码创建后,就为每一个页码监听一个click事件。                    if (pNum > 1) {                        pNum--;                        getPageData(pNum); //点击后就去执行取页数据的操作。                        $("#pNum").html(pNum);                    }                    else                    { alert("已经是第一页了!") }                });                //下一页----------------------------------------------------                $("#next").click(function() {                    if (pNum < pageNo) {                        pNum++;                        getPageData(pNum);                        $("#pNum").html(pNum);                    } else {                        alert("已经是最后1页了!");                    }                });                //首页-------------------------------------------------                $("#first").click(function() {                    pNum = 1;                    getPageData(1);                    $("#pNum").html(1);                });                //尾页-------------------------------------------------                $("#last").click(function() {                    pNum = pageNo;                    getPageData(pageNo);                    $("#pNum").html(pageNo);                });                //Go按钮-------------------------------------------------                $("#go").click(function() {                    pNum = $("#goNum").val();                    if ((pNum >= 1) && (pNum <= 10)) {                        getPageData(pNum);                        $("#pNum").html(pNum);                    }                    else                    { alert("请输入正确的页数!"); }                });                //-------------------------------------------------            }        });        //----------------------------------------------------------------------------    });</script> <ul id="Comment"></ul><br /> 页数:<table id="pageNo"></table> 当前页:第<span id="pNum"></span>页 / 每页条数:<span id="pageCount"></span>条/总条数:<span id="counts"></span>条<input  type="button" value="首1页" id="first"/> <input  type="button" value="上一页" id="prev"/> <input  type="button" value="下一页"  id="next"/> <input  type="button" value="尾页" id="last"/>         跳转的页数:<input type="text" id="goNum"/> <input type="button"  id="go" value="Go"/>    </div>    </form></body></html>


 

原创粉丝点击