代码改变世界

分页

2012-09-25 16:53  露珠的微笑  阅读(215)  评论(0)    收藏  举报

自己练习分页功能效果如下:

静态模版一:

<!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>    

<title>$appParam.TitleName$</title>

            $appParam.CssFiles$

            $appParam.AjaxProClientCode$

            $appParam.JSFiles$ </head>

<body onload="search(1)">

</body>

</html>

显示数据的模版:

<form>
<table>
<thead>
      <th >Vendor Code</th>
      <th> Name</th>
      <th> Address</th>
      <th>City</th>
      <th>State</th>
      <th>Zip</th>
</thead>
<tbody id="tbody">
<ad:if test="$comparenocase(vendornameList.Count, 0)$">
             <tr>
                <td  colspan="6" bgcolor="#ffffff" >Have no record temporary Search.</td>
              </tr>    
        <ad:else>
           <ad:foreach collection="$vendornameList$" var="items" index="i">
                 <tr class="vendorR" onclick="GetVendor($items.ID$,'$items.Name$')">
                       <td>
                           $items.VendorNum$
                        </td>
                         <td>
                           $items.Name$
                        </td>
                         <td>
                           $items.Address$
                        </td>
                         <td>
                           $items.City$
                        </td>
                         <td>
                           $items.Stpr$
                        </td>
                         <td>
                           $items.Zippostal$
                        </td>
                      </tr>
                </ad:foreach>
        </ad:if>
       
        <tr>
    <td colspan="6">  
        <div style="float: right; padding-right: 20px; line-height:1" class="pagination"
            pagesize="$pagesize$" currentpage="$pageindex$" totalcount="$totalcount$" id="Pagination">
        </div>
 
<ad:if test="$comparenocase(vendornameList.Count, 0)$">
       <input id="pagesizeleng" name="pagesizeleng" type="hidden" value="0"  />
    <ad:else>
      <input id="pagesizeleng" name="pagesizeleng" type="hidden" value="$totalcount$"  />
    </ad:if>
</td>
</tr>
       
       
    </tbody>
</table>
</form>

JavaScript文件内容:

function search(page) {    

var htm = Survey.TestT.Get_Vendorname(page).value;    ///读取数据库的数据

$("body").html(htm);       //数据显示在模版中

//Rebind Quick Pager    

$(".pagination").pagination(parseInt($("#Pagination").attr("totalcount")), {        

  items_per_page: parseInt($("#Pagination").attr("pagesize")),        

   num_edge_entries: 2,        

     num_display_entries: 5,

     prev_text: "Prev",     

     next_text: "Next",      

    current_page: parseInt($("#Pagination").attr("currentpage")),       

    link_to: "javascript:void(0);",     

    callback: pageselectCallbackBySearch    

});

}

 

function pageselectCallbackBySearch(id) {

    search(id + 1);

}

 

c#后台代码:

// ============================================================ //

Created By:Qiuhua,Huang, Survey_20120925, 25/09/2012

// ============================================================

using System; using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Net;

using System.Web.UI.HtmlControls;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Net.Mail;

using Survey.publicCS;

using BLL; using DAL;

namespace Survey {    

    public partial class TestT : BasePage    

      {             

       private string modelFile = "TestT.htm";

                  private Triwow.Common.Engineer.ApplicationParam ap = null;

       Ader.TemplateEngine.TemplateManager tm = null;

               protected void Page_Load(object sender, EventArgs e)         {         

              ap = new Triwow.Common.Engineer.ApplicationParam(typeof(Survey.TestT));          

             ap.TitleName = Triwow.Common.Config.ApplicationConfiguration.GetSetting("WebPageTitle", "TestT");   

                ap.CssFiles = "Css/popup.css;Css/pagination.css;";//多个可用分号分隔     

                ap.JSFiles = "Js/jquery-1.7.1.js;JsForPage/test.js;Js/jquery.pagination.js";//多个可用分号分隔

                             //EN:Reads the template through the template engin      

                  //CN:通过模板引擎读取模板

                        tm = Ader.TemplateEngine.TemplateManager.FromFile(Server.MapPath(ap.TemplatePath + modelFile));

                           tm.SetValue("appParam", ap);

                     Response.Write(tm.Process());     

    }

 

///从数据库读取数据

        [AjaxPro.AjaxMethod]

        public string Get_Vendorname(int pages)

        {

            Ader.TemplateEngine.TemplateManager tm1 = null;

            Triwow.Common.Engineer.ApplicationParam ap1 = new Triwow.Common.Engineer.ApplicationParam(typeof(Survey.TestT));

            tm1 = Ader.TemplateEngine.TemplateManager.FromFile(Server.MapPath(ap1.TemplatePath + "test.htm"));

            BLL_Set s = new BLL_Set();

            object[] obj = { pages, 3 };

            List<Vendor> lll = s.Get_VendorName(BasePage.getConn(), obj);

            if (lll.Count > 0)

            {

                tm1.SetValue("paging", 1);

                tm1.SetValue("pagesize", 3);                          //每页显示3条

                tm1.SetValue("totalcount", lll[0].ICount);     //总共条数

                tm1.SetValue("pageindex", (pages - 1));

                tm1.SetValue("vendornameList", lll);

            }

            else

            {

                tm1.SetValue("vendornameList", "");

            }

            return tm1.Process();

        }

    }

}

 

分页存储过程:

USE [survey] GO

/****** Object:  StoredProcedure [dbo].[pro_GetVendorName]    Script Date: 09/25/2012 16:35:04 ******/

SET ANSI_NULLS ON

GO SET QUOTED_IDENTIFIER ON GO

-- =============================================

-- Author:  Qiuhua,huang -- Create date: 17/09/2012

-- Description: get Company information for SelectVendor  in "assign survey" page

-- =============================================

--pro_GetVendorName 1,20 ALTER PROCEDURE [dbo].[pro_GetVendorName] @pageIndex1 int, @pageSize1 int

AS BEGIN

  declare @sql1 varchar(8000)

  declare @sql2 varchar(8000)

  declare @sql3 varchar(8000)

  declare @pageIndex int set @pageIndex=@pageIndex1  

  declare @pageSize int set @pageSize=@pageSize1  

  DECLARE @StartPoint VARCHAR(10)

  DECLARE @EndPoint VARCHAR(10)

 

  SELECT @StartPoint = @PageSize * ( @PageIndex - 1 ) + 1 ,

              @EndPoint = @StartPoint + @PageSize - 1    

 

set @sql1='DECLARE @Results TABLE  

            (  ID_IDENTITY INT IDENTITY PRIMARY KEY,

         id int,        

             name varchar(200),

         address varchar(200),

            vendornum varchar(50),

            stpr varchar(100),

            zippostal varchar(100),

          city varchar(100)      )     '

set @sql2='   insert into @Results(   id,

                  name,   

                  address,  

                  vendornum,   

                  stpr,   

                  zippostal,   

                  city   )  

       SELECT DISTINCT

                  (tb1.ID),

                  tb1.name,     

                  tb1.address,     

                  tb1.VendorNum,     

                  tb1.StPr,     

                  tb1.ZipPostal,     

                  tb1.City    

                            FROM Company as tb1   '  

set @sql3='  

    DECLARE @iCount AS int  

    SELECT @iCount = MAX(ID_IDENTITY) FROM @Results    

    SELECT         iCount = @iCount,

                id,

            name,   

            address,   

            vendornum as vendornum,   

            stpr,  

           zippostal,  

           city   

    FROM   @Results   

    WHERE   ID_IDENTITY BETWEEN '+@StartPoint+' AND '+@EndPoint             

print(@sql1+@sql2+@sql3)  

exec(@sql1+@sql2+@sql3)                   

END

 

 

c#

引入的两个文件,一个Js库文件分别如下:

pagination.css

View Code
.pagination {
            font-size: 11px;
        }
        
.pagination a {
    text-decoration: none;
    border: solid 1px #cdcdcd;
    color: #333;
}

.pagination a:hover
{
    color:blue;
}

.pagination a, .pagination span {
    display: block;
    float: left;
    padding-left: 4px;
    padding-right: 4px;
    margin-right: 5px;
    text-align:center;
    background:#ffffff
}

.pagination .current {
    
    color: blue;
    
}

.pagination .current.prev, .pagination .current.next{
    color:#666;
    border-color:#cdcdcd;
    background:#ffffff;
}



.pagination1 {
            font-size: 11px;
        }
        
.pagination1 a {
    text-decoration: none;
    border: solid 1px #cdcdcd;
    color: #69c000;
}

.pagination1 a, .pagination1 span {
    display: block;
    float: left;
    padding-left: 4px;
    padding-right: 4px;
    margin-right: 5px;
    text-align:center;
    background:#ffffff
}

.pagination1 .current {
    
    color: #69c000;
    
}

.pagination1 .current.prev, .pagination1 .current.next{
    color:#666;
    border-color:#cdcdcd;
    background:#ffffff;
}

jquery.pagination.js

View Code
/**
* This jQuery plugin displays pagination links inside the selected elements.
*
* @author Gabriel Birke (birke *at* d-scribe *dot* de)
* @version 1.1
* @param {int} maxentries Number of entries to paginate
* @param {Object} opts Several options (see README for documentation)
* @return {Object} jQuery Object
*/
jQuery.fn.pagination = function(maxentries, opts) {
    opts = jQuery.extend({
        items_per_page: 10,
        num_display_entries: 10,
        current_page: 0,
        num_edge_entries: 0,
        link_to: "#",
        prev_text: "Prev",
        next_text: "Next",
        ellipse_text: "...",
        prev_show_always: true,
        next_show_always: true,
        callback: function() { return false; }
    }, opts || {});

    return this.each(function() {
        /**
        * Calculate the maximum number of pages
        */
        function numPages() {
            return Math.ceil(maxentries / opts.items_per_page);
        }

        /**
        * Calculate start and end point of pagination links depending on 
        * current_page and num_display_entries.
        * @return {Array}
        */
        function getInterval() {
            var ne_half = Math.ceil(opts.num_display_entries / 2);
            var np = numPages();
            var upper_limit = np - opts.num_display_entries;
            var start = current_page > ne_half ? Math.max(Math.min(current_page - ne_half, upper_limit), 0) : 0;
            var end = current_page > ne_half ? Math.min(current_page + ne_half, np) : Math.min(opts.num_display_entries, np);
            return [start, end];
        }

        /**
        * This is the event handling function for the pagination links. 
        * @param {int} page_id The new page number
        */
        function pageSelected(page_id, evt) {
            current_page = page_id;
            drawLinks();
            var continuePropagation = opts.callback(page_id, panel);
            if (!continuePropagation) {
                if (evt.stopPropagation) {
                    evt.stopPropagation();
                }
                else {
                    evt.cancelBubble = true;
                }
            }
            return continuePropagation;
        }

        /**
        * This function inserts the pagination links into the container element
        */
        function drawLinks() {
            panel.empty();
            var interval = getInterval();
            var np = numPages();
            // This helper function returns a handler function that calls pageSelected with the right page_id
            var getClickHandler = function(page_id) {
                return function(evt) { return pageSelected(page_id, evt); }
            }
            // Helper function for generating a single link (or a span tag if it'S the current page)
            var appendItem = function(page_id, appendopts) {
                page_id = page_id < 0 ? 0 : (page_id < np ? page_id : np - 1); // Normalize page id to sane value
                appendopts = jQuery.extend({ text: page_id + 1, classes: "" }, appendopts || {});
                if (page_id == current_page) {
                    if (appendopts.classes) {
                        var lnk = $("<a class='noclick' >" + (appendopts.text) + "</a>");
                    }
                    else {
                        var lnk = $("<a class='current'>" + (appendopts.text) + "</a>");
                    }
                }
                else {
                    var lnk = $("<a>" + (appendopts.text) + "</a>")
                        .bind("click", getClickHandler(page_id))
                        .attr('href', opts.link_to.replace(/__id__/, page_id));


                }

                if (appendopts.classes) {
                    lnk.addClass(appendopts.classes);

                }

                panel.append(lnk);
            }
            // Generate "Previous"-Link
            if (opts.prev_text && (current_page > 0 || opts.prev_show_always)) {
                appendItem(current_page - 1, { text: opts.prev_text, classes: "prev" });
            }
            // Generate starting points
            if (interval[0] > 0 && opts.num_edge_entries > 0) {
                var end = Math.min(opts.num_edge_entries, interval[0]);
                for (var i = 0; i < end; i++) {

                    appendItem(i);
                }
                if (opts.num_edge_entries < interval[0] && opts.ellipse_text) {
                    jQuery("<a>" + opts.ellipse_text + "</a>").appendTo(panel);
                }
            }
            // Generate interval links
            for (var i = interval[0]; i < interval[1]; i++) {
                appendItem(i);
            }
            // Generate ending points
            if (interval[1] < np && opts.num_edge_entries > 0) {
                if (np - opts.num_edge_entries > interval[1] && opts.ellipse_text) {
                    jQuery("<a>" + opts.ellipse_text + "</a>").appendTo(panel);
                }
                var begin = Math.max(np - opts.num_edge_entries, interval[1]);
                for (var i = begin; i < np; i++) {
                    appendItem(i);
                }

            }
            // Generate "Next"-Link
            if (opts.next_text && (current_page < np - 1 || opts.next_show_always)) {
                appendItem(current_page + 1, { text: opts.next_text, classes: "next" });
            }
        }

        // Extract current_page from options
        var current_page = opts.current_page;
        // Create a sane value for maxentries and items_per_page
        maxentries = (!maxentries || maxentries < 0) ? 1 : maxentries;
        opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0) ? 1 : opts.items_per_page;
        // Store DOM element for easy access from all inner functions
        var panel = jQuery(this);
        // Attach control functions to the DOM element 
        this.selectPage = function(page_id) { pageSelected(page_id); }
        this.prevPage = function() {
            if (current_page > 0) {
                pageSelected(current_page - 1);
                return true;
            }
            else {
                return false;
            }
        }
        this.nextPage = function() {
            if (current_page < numPages() - 1) {
                pageSelected(current_page + 1);
                return true;
            }
            else {
                return false;
            }
        }
        // When all initialisation is done, draw the links
        drawLinks();
    });
}