asp.net分页和 jquery ajax 无刷新分页

asp.net分页

前台页面

 

!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">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
        <div>
            <asp:Button ID="btnFirst" runat="server" Text="第一页" οnclick="btnFirst_Click" />
            <asp:Button ID="btnPre" runat="server" Text="上一页" οnclick="btnPre_Click" />
            <asp:Button ID="btnNext" runat="server" Text="下一页" οnclick="btnNext_Click" />
            <asp:Button ID="btnLast" runat="server" Text="最后一页" οnclick="btnLast_Click" /></div>
    </div>
    </form>
</body>
</html>

 

后台代码

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        int pagesize = 10;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ViewState["pageindex"] = 1;
                GetLastPageIndex();//获取总页数
                LoadArticle(Convert.ToInt32(ViewState["pageindex"]), pagesize);//加载分页数据
            }
        }
        private void GetLastPageIndex()
        {
            string sqlstr = ConfigurationManager.ConnectionStrings["sqlserverstr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sqlstr))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    conn.Open();
                    cmd.CommandText = "select count(*) from T_Article";
                    int count = Convert.ToInt32(cmd.ExecuteScalar());
                    if (count % pagesize == 0)
                    {
                        ViewState["lastpageindex"] = count / pagesize;
                    }
                    else
                    {
                        ViewState["lastpageindex"] = count / pagesize + 1;
                    }
                }
            }
        }
        //加载分页数据
        private void LoadArticle(int pageindex, int pagesize)
        {
            DataTable dt = new DataTable();
            string sqlstr = ConfigurationManager.ConnectionStrings["sqlserverstr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sqlstr))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from (select ROW_NUMBER() over(order by ArticleId) as rownumber,* from T_Article)t where t.rownumber>(@pageindex-1)*@pagesize and t.rownumber<=@pageindex*@pagesize";
                    cmd.Parameters.AddWithValue("@pageindex", pageindex);
                    cmd.Parameters.AddWithValue("@pagesize", pagesize);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dt);
                }
            }
            if (dt.Rows.Count > 0)
            {
                this.GridView1.DataSource = dt;
                this.GridView1.DataBind();
            }
        }
        protected void btnFirst_Click(object sender, EventArgs e)
        {
            ViewState["pageindex"] = 1;
            LoadArticle(Convert.ToInt32(ViewState["pageindex"]), pagesize);
        }

        protected void btnPre_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(ViewState["pageindex"]);
            if (pageindex > 1)
            {
                pageindex--;
                ViewState["pageindex"] = pageindex;
                LoadArticle(Convert.ToInt32(ViewState["pageindex"]), pagesize);
            }

        }

        protected void btnNext_Click(object sender, EventArgs e)
        {
            int pageindex = Convert.ToInt32(ViewState["pageindex"]);
            if (pageindex < Convert.ToInt32(ViewState["lastpageindex"]))
            {
                pageindex++;
                ViewState["pageindex"] = pageindex;
                LoadArticle(Convert.ToInt32(ViewState["pageindex"]), pagesize);
            }
        }

        protected void btnLast_Click(object sender, EventArgs e)
        {
            ViewState["pageindex"] = ViewState["lastpageindex"];
            LoadArticle(Convert.ToInt32(ViewState["pageindex"]), pagesize);

        }
    }
}

 

 

 

无刷新分页

前台页面

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
    table
    {
        border:1px solid gray;
        width:700px;
        }
        table tr th,td
        {
             border:1px solid gray;           
            }
    </style>
    <script src="script/jquery-1.10.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            var pageindex = 1;
            var pagesize = 1;
            var pagesize1 = 0;
 
         
                $.ajax({
                    type: "post",
                    contentType: "application/json",
                    url: "WebService1.asmx/GetLastPageIndex",
                    data: "{pagesize:"+pagesize+"}",
                    success: function (data) {
                      pagesize1 = data.d;
                    }
                })
   
            LoadArticleJs();
            /*页面首次加载时调用后台的LoadArticle方法填充第一页的数据*/
            function LoadArticleJs() {
                $.ajax({
                    type: "post",
                    contentType: "application/json",
                    url: "WebService1.asmx/LoadArticle",
                    data: "{pageindex:" + pageindex + ",pagesize:" + pagesize + "}",
                    success: function (data) {
                    /*通过调试发现data.d就是一个集合,包含10个元素,每个元素里面都有ArticleId,ArticleTitle,ArticleContent,UserName四个属性,所以通过拼接表格的方式将数据呈现出来*/
                        var strtable = "<table>";
                        strtable += "<tr><th>编号</th><th>标题</th><th>内容</th><th>作者</th></tr>"
                        for (var i = 0; i < data.d.length; i++) {
                            strtable += "<tr><td>" + data.d[i].ArticleId + "</td><td>" + data.d[i].ArticleTitle + "</td><td>" + data.d[i].ArticleContent + "</td><td>" + data.d[i].UserName + "</td></tr>";
                        }
                        strtable += "</table>";
                        $('#divArticle table').remove();
                        $('#divArticle').append(strtable);
                    },
                    error: function () {
                        alert('获取数据失败');
                    }
                })
            }
            //下一页
            $('#btnNext').bind('click', function () {
                if (pageindex<pagesize1) {
                 pageindex++;
                LoadArticleJs();
                }
              
            })
            //上一页
            $('#btnPre').bind('click', function () {
                if (pageindex>1) {
                 pageindex--;
                LoadArticleJs();
                }
            })
            $('#btnFirst').bind('click', function () {
                pageindex = 1;
                LoadArticleJs();
            })
            $('#btnLast').bind('click', function () {
           
                pageindex = pagesize1;
                LoadArticleJs();
            })
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="divArticle">
        </div>
        <div>
            <input id="btnFirst" type="button" value="第一页" />
            <input id="btnPre" type="button" value="上一页" />
            <input id="btnNext" type="button" value="下一页" />
            <input id="btnLast" type="button" value="最后一页" />
        </div>
    </div>
    </form>
</body>
</html>

 

web服务页面   WebService1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;

namespace WebApplication1
{
    /// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
     [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
           [WebMethod]
       public int GetLastPageIndex(int pagesize)
        {
               int pageindex;
            string sqlstr = ConfigurationManager.ConnectionStrings["sqlserverstr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sqlstr))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    conn.Open();
                    cmd.CommandText = "select count(*) from Product";
                    int count = Convert.ToInt32(cmd.ExecuteScalar());
                   pageindex= Convert.ToInt32( Math.Ceiling(Convert.ToDouble(cmd.ExecuteScalar()) / pagesize));
                    //if (count % pagesize == 0)
                    //{
                    //    pageindex = count / pagesize;
                    //}
                    //else
                    //{
                    //    ViewState["lastpageindex"] = count / pagesize + 1;
                    //}
                   return pageindex;
                }
            }
        }
        [WebMethod]
        public List<Article> LoadArticle(int pageindex, int pagesize)
        {
            DataTable dt = new DataTable();
            string sqlstr = ConfigurationManager.ConnectionStrings["sqlserverstr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sqlstr))
            {
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "select * from (select ROW_NUMBER() over(order by ProductId) as rownumber,* from Product)t where t.rownumber>(@pageindex-1)*@pagesize and t.rownumber<=@pageindex*@pagesize";
                    cmd.Parameters.AddWithValue("@pageindex", pageindex);
                    cmd.Parameters.AddWithValue("@pagesize", pagesize);
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    adapter.Fill(dt);
                }
            }
            List<Article> list = new List<Article>();
            if (dt.Rows.Count>0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    Article myariticle = new Article();
                    myariticle.ArticleId = row["ProductId"].ToString();
                    myariticle.ArticleTitle = row["ProductImg"].ToString();
                    myariticle.ArticleContent = row["ProductName"].ToString();
                    myariticle.UserName = row["ProductPrice"].ToString();
                    list.Add(myariticle);
                }
            }
            return list;
        }
    }
    public class Article
    {
        public string ArticleId { get; set; }
        public string ArticleTitle { get; set; }
        public string ArticleContent { get; set; }
        public string UserName { get; set; }
    }
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值