Ajax+Asp.Net无刷新分页

Posted 涂山吕吕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Ajax+Asp.Net无刷新分页相关的知识,希望对你有一定的参考价值。

1、新建解决方案,并建立四个项目BLL,DAL,Model,PagerTest,如图所示:

2、Model代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Model
{
    public class Person
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 名字
        /// </summary>
        public string Name { get; set; }
    }
}
View Code

 

3、DAL代码

SQlHelper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace DAL
{
    public class SQlHelper
    {
        /// <summary>
        /// 执行非查询
        /// </summary>
        /// <param name="connectionString">连接字符串</param>
        /// <param name="cmdType">命令类型</param>
        /// <param name="cmdText">命令的文本</param>
        /// <param name="commandParameters">命令的参数</param>
        /// <returns>返回影响的结果集行数</returns>
        public static int ExcuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                PrePareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                int val = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                return val;
            }
        }


        /// <summary>
        /// 执行非查询
        /// </summary>
        /// <param name="connection">数据库连接</param>
        /// <param name="cmdType">命令的类型</param>
        /// <param name="cmdText">命令的文本</param>
        /// <param name="commandParameters">命令的参数</param>
        /// <returns>返回影响的结果集行数</returns>
        public static int ExcuteNonQuery(SqlConnection connection, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();

            PrePareCommand(cmd, connection, null, cmdType, cmdText, commandParameters);
            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行非查询
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="cmdType">命令的类型</param>
        /// <param name="cmdText">命令的文本</param>
        /// <param name="commandParameters">命令的参数</param>
        /// <returns>返回影响的结果集行数</returns>
        public static int ExcuteNonQuery(SqlTransaction tran, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            PrePareCommand(cmd, tran.Connection, tran, cmdType, cmdText, commandParameters);

            int val = cmd.ExecuteNonQuery();
            cmd.Parameters.Clear();
            return val;
        }

        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="connectionString">练级字符串</param>
        /// <param name="cmdType">命令的类型</param>
        /// <param name="cmdText">命令的文本</param>
        /// <param name="commandParameters">命令的参数数组</param>
        /// <returns>返回结果集</returns>
        public static SqlDataReader ExecuteReader(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectionString);
            try
            {
                PrePareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return sdr;
            }
            catch
            {
                conn.Close();
                throw;
            }
        }

        /// <summary>
        /// 执行查询
        /// </summary>
        /// <param name="connectionString">练级字符串</param>
        /// <param name="cmdType">命令的类型</param>
        /// <param name="cmdText">命令的文本</param>
        /// <param name="commandParameters">命令的参数数组</param>
        /// <returns>返回结果集</returns>
        public static SqlDataReader ExecuteReader(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
        {
            SqlCommand cmd = new SqlCommand();
            try
            {
                PrePareCommand(cmd, trans.Connection, trans, cmdType, cmdText, commandParameters);
                SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.Default);
                cmd.Parameters.Clear();
                return sdr;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 读取数据
        /// </summary>
        /// <param name="connectionString">数据库连接字符串</param>
        /// <param name="cmdType">数据命令类型</param>
        /// <param name="cmdText">数据命令的文本</param>
        /// <param name="cmd">需要被执行的数据命令</param>
        /// <param name="commandParameters">数据命令的参数</param>
        /// <returns>返回影响的结果集行数</returns>
        public static SqlDataReader ExecuteReader(string connectiongStr, CommandType cmdType, string cmdText, out SqlCommand cmd, params SqlParameter[] commandParameters)
        {
            cmd = new SqlCommand();
            SqlConnection conn = new SqlConnection(connectiongStr);
            try
            {
                PrePareCommand(cmd, conn, null, cmdType, cmdText, commandParameters);
                SqlDataReader sdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return sdr;
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 匹配参数
        /// </summary>
        /// <param name="cmd">需要被执行的数据命令</param>
        /// <param name="conn">数据库连接</param>
        /// <param name="trans">事务</param>
        /// <param name="cmdType">数据命令类型</param>
        /// <param name="cmdText">数据命令的文本</param>
        /// <param name="cmdParms">数据命令的参数</param>
        private static void PrePareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
        {
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }

            cmd.Connection = conn;
            cmd.CommandText = cmdText;

            if (trans != null)
            {
                cmd.Transaction = trans;
            }

            cmd.CommandType = cmdType;

            if (cmdParms != null)
            {
                foreach (SqlParameter param in cmdParms)
                {
                    cmd.Parameters.Add(param);
                }
            }
        }



    }
}
View Code

PersonDAL.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.ComponentModel;

namespace DAL
{
    public class PersonDAL
    {
        private static readonly string connStr = ConfigurationManager.ConnectionStrings["PagerTestConnectionString"].ToString();

        /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns>返回一个总数</returns>
        public  int GetPersonCount()
        {
            int i = 0;
            using (SqlDataReader sdr = SQlHelper.ExecuteReader(connStr, CommandType.Text, "select * from Person", null))
            {
                while (sdr.Read())
                {
                    i++;
                }
                sdr.Close();
                return i;
            }
        }

        /// <summary>
        /// 分页数据列表
        /// </summary>
        /// <param name="strGetFields">需要返回的列 </param>
        /// <param name="fldName">排序的字段名</param>
        /// <param name="PageSize">页尺寸</param>
        /// <param name="PageIndex">页码</param>
        /// <param name="doCount">返回记录总数, 非 0 值则返回</param>
        /// <param name="OrderType">设置排序类型, 非 0 值则降序</param>
        /// <param name="strWhere">查询条件 (注意: 不要加 where)</param>
        /// <returns></returns>
        public BindingList<Model.Person> Getlist(string strGetFields, string fldName, int PageSize, int PageIndex, int doCount, int OrderType, string strWhere)
        {
            SqlParameter[] parameters = {
                    new SqlParameter("@tblName", SqlDbType.VarChar, 500),
                    new SqlParameter("@strGetFields", SqlDbType.VarChar, 1000),
                    new SqlParameter("@fldName", SqlDbType.VarChar, 255),
                    new SqlParameter("@PageSize", SqlDbType.Int),
                    new SqlParameter("@PageIndex", SqlDbType.Int),
                    new SqlParameter("@doCount", SqlDbType.Bit),
                    new SqlParameter("@OrderType", SqlDbType.Bit),
                    new SqlParameter("@strWhere", SqlDbType.VarChar,1500),
                    };
            parameters[0].Value = "dbo.Person";
            parameters[1].Value = strGetFields;
            parameters[2].Value = fldName;
            parameters[3].Value = PageSize;
            parameters[4].Value = PageIndex;
            parameters[5].Value = doCount;
            parameters[6].Value = OrderType;
            parameters[7].Value = strWhere;
          SqlDataReader sdr=   SQlHelper.ExecuteReader(connStr, CommandType.StoredProcedure, "dbo.sp_Common_GetListByPage", parameters);

          BindingList<Model.Person> list = new BindingList<Model.Person>();
          while (sdr.Read())
          {
              list.Add(createRpCcInfoByReader(sdr));
          }

          return list;
        }

        /// <summary>
        /// 根据reader生成Person实体
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private Model.Person createRpCcInfoByReader(SqlDataReader reader)
        {
            Model.Person p = new Model.Person();
            p.Id = Convert.ToInt32(reader["Id"]); ;
            p.Name = Convert.ToString(reader["Name"]);
            return p;
        }
    }
}
View Code

 

4、BLL代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.ComponentModel;

namespace BLL
{
    public class PersonBLL
    {
         /// <summary>
        /// 获取总数
        /// </summary>
        /// <returns>返回一个总数</returns>
        public  int GetPersonCount()
        {
            DAL.PersonDAL p = new DAL.PersonDAL();
            return p.GetPersonCount();
        }

         /// <summary>
        /// 分页数据列表
        /// </summary>
        /// <param name="strGetFields">需要返回的列 </param>
        /// <param name="fldName">排序的字段名</param>
        /// <param name="PageSize">页尺寸</param>
        /// <param name="PageIndex">页码</param>
        /// <param name="doCount">返回记录总数, 非 0 值则返回</param>
        /// <param name="OrderType">设置排序类型, 非 0 值则降序</param>
        /// <param name="strWhere">查询条件 (注意: 不要加 where)</param>
        /// <returns></returns>
        public BindingList<Model.Person> Getlist(string strGetFields, string fldName, int PageSize, int PageIndex, int doCount, int OrderType, string strWhere)
        {
            DAL.PersonDAL p = new DAL.PersonDAL();
            return p.Getlist(strGetFields, fldName, PageSize, PageIndex, doCount, OrderType, strWhere);
        }
    }
}
View Code

 

5、PagerTest代码,

PagerHandler.ashx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.Text;

namespace PagerTest.Handler
{
    /// <summary>
    /// PagerHandler 的摘要说明
    /// </summary>
    public class PagerHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";


            string str = string.Empty;

            //具体的页面数
            int pageIndex;
            int.TryParse(context.Request["pageIndex"], out pageIndex);

            //页面显示条数
            int size = Convert.ToInt32(context.Request["pageSize"]);

            if (pageIndex == 0)
            {
                pageIndex = 1;
            }

            int count;
            BindingList<Model.Person> list = new BLL.PersonBLL().Getlist(
                "*",
                "Id",
                size, 
                pageIndex, 
                0, 
                1,
                 ""
                );

            StringBuilder sb = new StringBuilder();
            foreach (Model.Person p in list)
            {
                sb.Append("<tr><td>");
                sb.Append(p.Id.ToString());
                sb.Append("</td><td>");
                sb.Append(p.Name);
                sb.Append("</td></tr>");
            }
            str = sb.ToString();
            context.Response.Write(str);     
        }

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

PageWeb.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PageWeb.aspx.cs" Inherits="PagerTest.PageWeb" %>

<!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>
    <script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="Scripts/jquery.pagination.js" type="text/javascript"></script>
    <link href="Style/pagination.css" rel="stylesheet" type="text/css" />
   <link href="Style/tablecloth.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript">
        var pageIndex = 0;     //页面索引初始值
        var pageSize = 10;     //每页显示条数初始化,修改显示条数,修改这里即可
   
    $(function() {       
        InitTable(0);    //Load事件,初始化表格数据,页面索引为0(第一页)
                                                            
        //分页,PageCount是总条目数,这是必选参数,其它参数都是可选
        $("#Pagination").pagination(<%=pageCount %>, {
            callback: PageCallback,
            prev_text: \'上一页\',       //上一页按钮里text
            next_text: \'下一页\',       //下一页按钮里text
            items_per_page: pageSize,  //显示条数
            num_display_entries: 1,    //连续分页主体部分分页条目数
            current_page: pageIndex,   //当前页索引

以上是关于Ajax+Asp.Net无刷新分页的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET使用ajax实现分页局部刷新页面

(asp.net)点击按钮进行相应操作,怎么实现页面无刷新

ASP.NET MVC下Ajax.BeginForm方式无刷新提交表单

Ajax实现无刷新分页

在 Razor 视图中使用 Ajax 进行 Asp.Net Core 表分页

请问ASP.NET中当点击某个控件时(如Button)不想进行整个页面的刷新怎样设置?