使用Jquery Ajax对ASP.NET中GridView分页

来源:互联网 发布:淘宝买家号交易 编辑:程序博客网 时间:2024/06/08 09:26

源文件来自:

http://www.aspsnippets.com/Articles/Paging-in-ASPNet-GridView-using-jQuery-AJAX.aspx

 

小样下载:

http://www.aspsnippets.com/Handlers/DownloadFile.ashx?File=1b28e022-6fc1-469f-9eba-7ab6ec69382a.zip

 

1.        创建GridView

<asp:GridViewID="gvCustomers" runat="server"AutoGenerateColumns="false" RowStyle-BackColor="#A1DCF2"

    HeaderStyle-BackColor="#3AC0F2"HeaderStyle-ForeColor="White">

    <Columns>

        <asp:BoundFieldItemStyle-Width="150px" DataField="CustomerID" HeaderText="CustomerID"/>

        <asp:BoundFieldItemStyle-Width="150px" DataField="ContactName"HeaderText="Contact Name" />

        <asp:BoundFieldItemStyle-Width="150px" DataField="City"HeaderText="City" />

    </Columns>

</asp:GridView>

<br/>

<div class="Pager"></div>

 

2.        名称空间引用

using System.Data;

using System.Web.Services;

using System.Configuration;

using System.Data.SqlClient;

 

3.        表数据填充(实现存在表头)


privatestatic int PageSize = 10; // 分页数量

protectedvoid Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        BindDummyRow();

    }

}

 

privatevoid BindDummyRow()

{

    DataTable dummy = new DataTable();

    dummy.Columns.Add("CustomerID");

    dummy.Columns.Add("ContactName");

    dummy.Columns.Add("City");

    dummy.Rows.Add();

    gvCustomers.DataSource = dummy;

    gvCustomers.DataBind();

}

 

4.        SQL存储过程进行分页


CREATEPROCEDURE [dbo].[GetCustomers_Pager]

      @PageIndex INT = 1

      ,@PageSize INT = 10

      ,@RecordCount INT OUTPUT

AS

BEGIN

      SET NOCOUNT ON;

      SELECT ROW_NUMBER() OVER

      (

            ORDER BY [CustomerID] ASC

      )AS RowNumber

      ,[CustomerID]

      ,[CompanyName]

      ,[ContactName]

      ,[City]

      INTO #Results

      FROM [Customers]

    

      SELECT @RecordCount = COUNT(*)

      FROM #Results

          

      SELECT * FROM #Results

      WHERE RowNumber BETWEEN(@PageIndex -1) *@PageSize + 1 AND(((@PageIndex -1) * @PageSize + 1) + @PageSize) - 1

    

      DROP TABLE #Results

END

 

5.        jQuery Ajax调用WebMethod

 

[WebMethod]

publicstatic string GetCustomers(int pageIndex)

{

    string query = "[GetCustomers_Pager]";

    SqlCommand cmd = new SqlCommand(query);

    cmd.CommandType =CommandType.StoredProcedure;

   cmd.Parameters.AddWithValue("@PageIndex", pageIndex);

   cmd.Parameters.AddWithValue("@PageSize", PageSize);

    cmd.Parameters.Add("@RecordCount",SqlDbType.Int, 4).Direction = ParameterDirection.Output;

    return GetData(cmd, pageIndex).GetXml();

}

 

privatestatic DataSet GetData(SqlCommand cmd, int pageIndex)

{

    string strConnString =ConfigurationManager.ConnectionStrings["conString"].ConnectionString;

    using (SqlConnection con = newSqlConnection(strConnString))

    {

        using (SqlDataAdapter sda = newSqlDataAdapter())

        {

            cmd.Connection = con;

            sda.SelectCommand = cmd;

            using (DataSet ds = new DataSet())

            {

                sda.Fill(ds,"Customers");

                DataTable dt = newDataTable("Pager");

               dt.Columns.Add("PageIndex");

               dt.Columns.Add("PageSize");

               dt.Columns.Add("RecordCount");

                dt.Rows.Add();

               dt.Rows[0]["PageIndex"] = pageIndex;

               dt.Rows[0]["PageSize"] = PageSize;

               dt.Rows[0]["RecordCount"] =cmd.Parameters["@RecordCount"].Value;

                ds.Tables.Add(dt);

                return ds;

            }

        }

    }

}



6.        客户端的实现

此处注意jQuery的版次。因为live事件绑定,在1.9以上的版本使用的是on来进行绑定的


<scripttype="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<scriptsrc="ASPSnippets_Pager.min.js"type="text/javascript"></script>

<scripttype="text/javascript">

    $(function () {

        GetCustomers(1);

    });

    $(".Pager.page").live("click", function () {

        GetCustomers(parseInt($(this).attr('page')));

    });

    function GetCustomers(pageIndex) {

        $.ajax({

            type: "POST",

            url:"Default.aspx/GetCustomers",

            data: '{pageIndex: ' + pageIndex +'}',

            contentType:"application/json; charset=utf-8",

            dataType: "json",

            success: OnSuccess,

            failure: function (response) {

                alert(response.d);

            },

            error: function (response) {

                alert(response.d);

            }

        });

    }

 

    function OnSuccess(response) {

        var xmlDoc = $.parseXML(response.d);

        var xml = $(xmlDoc);

        var customers =xml.find("Customers");

        var row = $("[id*=gvCustomers]tr:last-child").clone(true);

        $("[id*=gvCustomers]tr").not($("[id*=gvCustomers] tr:first-child")).remove();

        $.each(customers, function () {

            var customer = $(this);

            $("td",row).eq(0).html($(this).find("CustomerID").text());

            $("td",row).eq(1).html($(this).find("ContactName").text());

            $("td",row).eq(2).html($(this).find("City").text());

           $("[id*=gvCustomers]").append(row);

            row = $("[id*=gvCustomers]tr:last-child").clone(true);

        });

        var pager =xml.find("Pager");

       $(".Pager").ASPSnippets_Pager({

            ActiveCssClass:"current",

            PagerCssClass: "pager",

            PageIndex:parseInt(pager.find("PageIndex").text()),

            PageSize:parseInt(pager.find("PageSize").text()),

            RecordCount:parseInt(pager.find("RecordCount").text())

        });

    };

</script>

7.        样式

 

<styletype="text/css">

    body

    {

        font-family: Arial;

        font-size: 10pt;

    }

    .Pager span

    {

        text-align: center;

        color: #999;

        display: inline-block;

        width: 20px;

        background-color: #A1DCF2;

        margin-right: 3px;

        line-height: 150%;

        border: 1px solid #3AC0F2;

    }

    .Pager a

    {

        text-align: center;

        display: inline-block;

        width: 20px;

        background-color: #3AC0F2;

        color: #fff;

        border: 1px solid #3AC0F2;

        margin-right: 3px;

        line-height: 150%;

        text-decoration: none;

    }

</style>

 

8.        结果

 

0 0
原创粉丝点击