asp.net original paging stored procedures and pagination instances

Source: Internet
Author: User
Tags table name

We'll take the SQL stored procedure first.

Paging stored procedures.

The code is as follows Copy Code

CREATE PROCEDURE [dbo]. [Proc_splitpage]
   --Add The parameters for the stored procedure here
    @tblName    VA Rchar (255),      --table name
    @strFields varchar (1000) = ' * ',--columns that need to be returned, Default *
    @strOrder varchar (255) = ',     --sorted field name, required
     @strOrderType varchar = ' ASC ',--Sort by default ASC
    @PageSize    int = 10,          -page size, default ten
    @PageIndex int = 1,           -page number, default 1
    @strWhere varchar (1500) = '--Query criteria ( Note: Do not add where)
as
declare @strSQL    varchar (5000)
If @strWhere!= '
Set @strWhere = ' where ' + @str Where

Set @strSQL =
' SELECT ' + @strFields + ' from (' +
' SELECT row_number () over (order by ' + @strOrder + ' + @strOrderType + ') as

POS, ' + @strFields + ' +
' From ' + @tblName + ' + @strWhere +
') as SP
WHERE Pos BETWEEN ' +str ((@PageIndex-1) * @PageSize + 1) + ' and ' +str (@PageIndex * @PageSize)


EXEC (@strSQL)


Below is a page-class pager{}

The code is as follows Copy Code

public class Pager


{


private string _firstpagetext;


<summary>


First page text display default display as "Home"


</summary>


public string Firstpagetext


{


get {


return string. IsNullOrEmpty (_firstpagetext)? "Home": _firstpagetext;


}


set {


_firstpagetext = value;


}


}

private string _prepagetext;


<summary>


Previous page text display defaults to previous page


</summary>


public string Prepagetext


{


Get


{


return string. IsNullOrEmpty (_prepagetext)? "Previous page": _prepagetext;


}


Set


{


_prepagetext = value;


}


}

private string _nextpagetext;


<summary>


The next page of text display defaults to "next"


</summary>


public string NextPageText


{


Get


{


return string. IsNullOrEmpty (_nextpagetext)? "Next page": _nextpagetext;


}


Set


{


_nextpagetext = value;


}


}

private string _lastpagetext;


<summary>


Last text display defaults to "last"


</summary>


public string Lastpagetext


{


Get


{


return string. IsNullOrEmpty (_lastpagetext)? "Last": _lastpagetext;


}


Set


{


_lastpagetext = value;


}


}

       ///<summary>
       / Total record number
       ///</summary>
         public int RecordCount {get; set;}

        private int _pagesize=15;
       ///<summary>
        Per page paging size defaults to
       ///</summary>
         public int PageSize {
            get {
                Return _pagesize = = 0? : _pagesize;
           }set{
                 _pagesize = value;
           }
       }

        private int _pageindex=1;
       ///<summary>
        Current page number
       ///</summary>
         public int PageIndex {
            get {
& nbsp;               return _pageIndex = 0? 1: _pageindex;
           }
            set {
                 _pageindex = value;
           }
       }

        private int _maxshowpagesize = 10;
       ///<summary>
        Displays the maximum number of page number lists by default of
       ///</summary>
         public int Maxshowpagesize {
             get {
                return _maxshowpagesize;
           }
            set {
                 _maxshowpagesize = value;
           }
       }

private string _querystringname;


&lt;summary&gt;


The name of the page number in the browser that passes the value defaults to page


&lt;/summary&gt;


public string Querystringname {


get {


return string. IsNullOrEmpty (_querystringname)? "Page": _querystringname;


}


set {


_querystringname = value;


}


}

<summary>
URL of the page
</summary>
public string URL {
get {
String url = httpcontext.current.request.url.absoluteuri;//Current page Absolute Road

Diameter
if (enableurlrewriting)//Use URL rewrite
{
Url=url. Substring (0, URL. LastIndexOf ("/") + 1)//Get the current page directory path

Diameter


URL + urlrewritepattern;


}


else {//normal with question mark page pass value


Demo.aspx


Demo.aspx?a=1


Demo.aspx?page=1


Demo.aspx?a=2&amp;page=1


if (URL. Contains ("aspx?")


{


if (Regex.IsMatch (url,@ "page=[0-9]*$", regexoptions.ignorecase))//

If a page=* string exists
{
url = regex.replace (URL, @ "page=[0-9]*$", "",

Regexoptions.ignorecase);//Replace page=* string


}


URL = + querystringname + "={0}";


}


else {


URL + "?" + Querystringname + "={0}";


}


}


return URL;


}


}

private bool _enableurlrewriting;


&lt;summary&gt;


Whether the URL overrides default to Flase


&lt;/summary&gt;


public bool Enableurlrewriting {


get {


Return (object) _enableurlrewriting = = null? False: _enableurlrewriting;


}


set {


_enableurlrewriting = value;


}


}

<summary>
Page URL rewrite rules, which use {0} instead of list-1-{0}.html for page number values, enabling this feature requires

The

Enableurlrewriting property is set to True
       ///</summary>
         public string Urlrewritepattern {get; set;}

        private String _classname;
       ///<summary>
        The CSS name for the paging container
       ///</summary>
         public string ClassName {
            get {
                return string . IsNullOrEmpty (_classname)? "Paginator": _classname;
           }set{
                 _classname = value;
           }
       }

        private String _currentpagecss;
       ///<summary>
        Current page button CSS
       ///</summary>
         public string Currentpagebuttoncss {
             get {
                return string. IsNullOrEmpty (_CURRENTPAGECSS)? "CPB": _currentpagecss;
           }set{
                 _currentpagecss = value;
           }
       }

        private bool _showspantext;
       ///<summary>
        Whether the text information in the Span label displays default to False does not show
       ///</summary>
         public bool Showspantext {
             get {
                 Return (object) _showspantext = = null? False: _showspantext;
           }
            set {
                 _showspantext = value;
           }
       }

        private String _spantextclass;
       ///<summary>
        Pagination Text description span label CSS
       ///</summary>
         public string Spantextclass {
             get {
                return string. IsNullOrEmpty (_spantextclass)? "STC": _spantextclass;
           }
            set {
                 _spantextclass = value;
           }
       }

        private String _submitbuttontext;
       ///<summary>
        OK button text display default display "OK"
       ///</summary>
         public string Submitbuttontext {
             get {
                 return string. IsNullOrEmpty (_submitbuttontext)? OK:

_submitbuttontext;
}
set {
_submitbuttontext = value;
}
}
}

Pagination displays the method of stitching HTML code:

The code is as follows Copy Code

public class Splitmanager


{


public static string Aspnetpagers (Pager Pager)


{


StringBuilder sb = new StringBuilder ();


String Attr= "";


int PageCount = 0;//The total number of layers of the current page


int floorcount = Total number of layers 0;//paging


int currentlastpage = 0;//page number of the current last page


int pagenum = Pager. Recordcount/pager. PageSize + 1;//Total pages 1~24


Sb. AppendFormat ("&lt;div class=" {0} "&gt;n", pager. ClassName);


Attr=pager. Pageindex==1? " Disabled=disabled ":" "//Flag The current page is the first page is equal to control

The validity of the first two buttons
Sb. AppendFormat (getahtml) (attr,string. Format

(Pager. url,1), Pager. Firstpagetext));//Add the first page of code
Sb. AppendFormat (getahtml (attr, String). Format (Pager. URL, Pager. PAGEINDEX-1),

Pager. Prepagetext);//Add the previous page's code
PageCount = Pager. Pageindex/pager. maxshowpagesize;//Current Page 0~1~2
PageCount = Pager. PageIndex% Pager. Maxshowpagesize = 0? Pagecount-1:

pagecount;//clears the status of one more divisor when the current number of pages is numbered as an integer multiple pages
Floorcount = Pagenum/pager. maxshowpagesize;//number of page layers 0~1~2
Currentlastpage=pagenum<pager. Maxshowpagesize * (PageCount + 1)?

Pagenum:pager. Maxshowpagesize * (PageCount + 1);
if (pager. PageIndex > Pager. Maxshowpagesize//////When the current ordinal is greater than the number of pages per page

Again front end ...
{
Sb. AppendFormat (Getahtml ("", String. Format (Pager. Url

Pager. Maxshowpagesize * PageCount), "...");


}


for (int i = pager. Maxshowpagesize * PageCount + 1; I &lt;= currentlastpage; i++)


{


if (i = = Pager. PageIndex)//To determine whether the loop page is the current page


{


Sb. AppendFormat (getspanhtml (i, pager). CURRENTPAGEBUTTONCSS));


}


else {


Sb. AppendFormat (Getahtml ("", String. Format (Pager. URL, i), i.tostring

()));
}
}
if (pager. PageIndex <= Pager. Maxshowpagesize * floorcount)//When the current ordinal number is less than the reciprocal

The second page page number is displayed on the back end ...
{
Sb. AppendFormat (Getahtml ("", String. Format (Pager. Url

Pager. Maxshowpagesize * (PageCount + 1) + 1), "...");
}
attr = Pager. PageIndex = = Pagenum? "Disabled=disabled": "";//Flag Current Page last

One page is equal to control the validity of the last two buttons
Sb. AppendFormat (getahtml (attr, String). Format (Pager. URL, Pager. PAGEINDEX+1),

Pager. NextPageText);//Add the next page of code
Sb. AppendFormat (getahtml (attr, String). Format (Pager. URL, Pagenum),

Pager. Lastpagetext);//Add last page code
if (pager. Showspantext)//Whether display pagination text span label display
{
Sb. AppendFormat ("<span class=") + pager. Spantextclass + "" > total {0} pages, per page

{1} Records n ", Pagenum, pager. PageSize);
Sb. AppendFormat ("to <input type=" input "id=" Jumpnum "

Style= "width:20px" name= "Jump" value= "{0}"/> page ", Pager. PageIndex = = Pagenum?

Pagenum:pager. PageIndex + 1);
Sb. AppendFormat ("<a href=" # "style=" Float:none; "

onclick= "Javascript:jump ();" > "+ pager. Submitbuttontext + "</a></span>n");
                sb. Append (Getjumpscript) (pager. )//Add the JavaScript code for the button jump
           }
             sb. AppendFormat ("</div>");//
            return sb. ToString ();
       }

       ///<summary>
       / Get the HTML of a label
       ///</summary>
   & nbsp;   ///<param name= "title" >a ' s title</param>
        ///<param name= "url" >the URL of a</param>
       /// <param name= "attr" >the attribute</param>
       ///<returns >return HTML string</returns>
        private static string getahtml ( String attr,string url,string title)
        {
             return "<a" + attr + "href=" "+url+" "style=" margin-

right:5px; " > "+title+" </a>n ";
}

<summary>
Get the HTML of a label
</summary>
<param name= "num" >the content of Span</param>
<param name= "ClassName" >class style name</param>
<returns>return HTML String </returns>
private static string getspanhtml (int num, string className)
{
Return "<span class=" "+ ClassName +" ">" + num + "</span>n";
}

&lt;summary&gt;


Get the JavaScript code for jumps


&lt;/summary&gt;


&lt;param name= "url" &gt; Current paging URL rule &lt;/param&gt;


&lt;returns&gt; return a JavaScript code &lt;/returns&gt;


private static string Getjumpscript (string url)


{


String scriptstr = "&lt;script type=" Text/javascript "&gt;n" +


"Function jump () {n" +


"Var Jnum=document.getelementbyid (" Jumpnum "). Value;n" +


"If (isNaN (jnum)) {n" +


Alert (in the Jump box, enter a number!) "); n" +


"}n" +


"Else{n" +


"Alert (jnum); n" +


"Location.href=string.format (" "+ URL +" ", jnum); n" +


"}n" +


"}n" +


"String.Format = function () {n" +


"if (Arguments.length = = 0) n" +


"Return null; N "+


"var str = arguments[0];" N "+


"For (var i=1;i&lt;arguments.length;i++) {n" +


"var re = new RegExp (' \\{' + (i-1) + ' \} ', ' GM '); n" +


"str = str.replace (Re, arguments[i]); n" +


"}n" +


"Return Str;n" +


"}n" +


"&lt;/script&gt;n";


return scriptstr;


}

}

The most streamlined and necessary parameters are passed in to show the paging effect:

The code is as follows Copy Code

protected string str = "";
protected void Page_Load (object sender, EventArgs e)
{
Pager Pager = new Pager () {RecordCount = 350,
PageSize = 15,
MAXSHOWPAGESIZE=10,
PageIndex = Convert.ToInt32 (request.querystring["page"),
Showspantext=true};
str = splitmanager.aspnetpagers (pager);

}

CSS for testing:

&lt;style type= "Text/css" &gt;


/* Pagination Style control start * *


. paginator {font:12px Arial, Helvetica, Sans-serif;


padding:10px 20px 10px 0;


margin:0px;}


. paginator a {border:solid 1px #ccc;


Color: #0063dc;


Cursor:pointer;


Text-decoration:none;}


. paginator a:visited {padding:1px 6px;


Border:solid 1px #ddd;


Background: #f0f1f1;


Text-decoration:none;}


. paginator. CPB {border:1px solid #14316b;


font-weight:700;


Color: #f0f1f1;


Background-color: #1f3d76;}


. paginator a:hover {border:solid 1px #14316b;


Color: #14316b;


Text-decoration:none;}


. paginator a,.paginator a:visited,.paginator. Cpb,.paginator a:hover{float:left;


height:16px;


line-height:16px;


min-

width:10px;_width:10px;


margin-right:5px;


Text-align:center;


White-space:nowrap;


font-size:12px;


Font-family:


Arial,simsun;


padding:0 3px;}


. paginator. Stc{color: #999; margin-left:20px;}


. paginator. STC a{margin-left:10px;


/* Pagination Style control end * *


&lt;/style&gt;

At the same time, in order to fit the paging, and then give a DataTable to the generic list of a method and a paging stored procedure.

This conversion method needs to match the corresponding entity class, and the field names of the corresponding tables in the entity class are case-insensitive.

The code is as follows Copy Code

#region DataTable to List/model

&lt;summary&gt;


DataTable to List


&lt;/summary&gt;


&lt;typeparam name= "Ttype" &gt;object type&lt;/typeparam&gt;


&lt;param name= "DT" &gt;DataTable&lt;/param&gt;


&lt;returns&gt;return a List Model type&lt;/returns&gt;


public static list&lt;t&gt; datatabletoobjectlist&lt;t&gt; (DataTable dt) where t:new ()


{


DataRowCollection DRC = dt. Rows;


int ColumnCount = DRC. Count;


list&lt;t&gt; result = new list&lt;t&gt; (); Declare the generic type of return


Type type = typeof (T);





propertyinfo[] Propertys = type. GetProperties

(bindingflags.ignorecase| bindingflags.instance| bindingflags.public| Bindingflags.setpropert

y); Get the collections of the model


foreach (DataRow R in DRC)


{


Result. ADD (datarowtoobjectmodel&lt;t&gt; (R, Propertys));


}


return result;





}





&lt;summary&gt;


DataRow to a Model


&lt;/summary&gt;


&lt;typeparam name= "T" &gt;the type of model&lt;/typeparam&gt;


&lt;param name= "R" &gt;DataRow&lt;/param&gt;


&lt;param name= "Propertys" &gt;the object to Model&lt;/param&gt;


&lt;returns&gt;return a Model type&lt;/returns&gt;


private static T datarowtoobjectmodel&lt;t&gt; (DataRow R, propertyinfo[] propertys)

where T:new ()


{


T t = new t ();


for (int i = 0; i &lt; Propertys. Length; i++)


{


Object obj = R[propertys[i]. Name];


if (obj!= null)


{


if (propertys[i). PropertyType = = typeof (int))


Propertys[i]. SetValue (t, Publicmethod.getint (obj), null);


if (propertys[i). PropertyType = = typeof (String)


Propertys[i]. SetValue (t, obj.) ToString (), NULL);


if (propertys[i). PropertyType = = typeof (DateTime))


Propertys[i]. SetValue (t, Publicmethod.getdatetime (obj), null);


}


}


return t;


}


#endregion


All right, so it's all KO.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.