Step by step create a beautiful news list (without refreshing pages, Content preview) Chapter 3

Source: Internet
Author: User

Let's take a look at the demand analysis:

3. =: Click the next page to trigger the event, call Ajax to search for the data on the next page in the database, and return the data on the page.

There are two events, both JS events. We use jqueryCode.

For paging, we use the pagination plug-in of jquery. The official address is http://plugins.jquery.com/project/paginationto download the JS file and CSS file (which is attached at the bottom)

Let's talk about its basic usage:

Like the jquery plug-in, this plug-in is easy to use. The method is pagination, for example, $ ("# page"). pagination (100);. Here, the 100 parameter is required, indicating the total number of projects, which is the simplest use.

For example, the following code is used:Copy codeThe Code is as follows: $ ("# pagination"). pagination (56 ,{
Num_edge_entries: 2,
Num_display_entries: 4,
Callback: pageselectcallback,
Items_per_page: 1
});

This Code indicates that there are a total of 56 (maxentries) list items, 2 (num_edge_entries) are displayed on the first and end sides of the page, and 4 (num_display_entries) are displayed on the number of consecutive pages, the callback function is pageselectcallback (callback). The list item displayed on each page is 1 (items_per_page ). You can modify the parameters here according to the parameter table.

Specific usage can refer to the official documentation or http://www.cnblogs.com/aosiyelong/archive/2010/03/30/1700262.html

Then we will talk about how to integrate it into our side.

Add the relevant JS files and CSS files in the newslist. ASPX page (bottom): jquery-1.4.1.js, pagination. jsCopy codeThe Code is as follows: <link type = "text/CSS" rel = "stylesheet" href = "CSS/newslist.css"/>
<Link type = "text/CSS" rel = "stylesheet" href = "CSS/pagination.css"/>
<SCRIPT src = "JS/jquery-1.4.1.js" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "JS/jquery. pagination. js" type = "text/JavaScript"> </SCRIPT>

Next, let's look at the key JS Code: Copy code The Code is as follows: <SCRIPT type = "text/JavaScript" Language = "JavaScript">
$ (). Ready (function (){
Initdata (0 );
});
// Process flip pages
Function pageselectcallback (page_id, JQ ){
// Alert (page_id );
Initdata (page_id );
};
Function initdata (pageindx)
{
VaR tbody = "";
VaR orderby = "news_id ";
$. Ajax ({
Type: "Post", // post Transmission
Datatype: "JSON", // JSON Data Format
URL: 'ajax/newshandler. ashx', // target address
Data: "pageno =" + (pageindx + 1) + "& orderby =" + orderby,
Success: function (JSON ){
$ ("# Producttable TR: GT (0)"). Remove ();
VaR productdata = JSON. News;
$. Each (productdata, function (I, n ){
VaR TRS = "";
TRS + = "<tr> <TD style = 'text-align: Center'> <a href = \" newsread. aspx? News_id = "+ N. news_id + "\" class = \ "info2 \"> "+ N. news_title + "</a> </TD> <TD style = 'text-align: Center'>" + N. news_readtimes + "</TD> <TD style = 'text-align: Center'>" + N. news_time + "</TD> </tr> ";
Tbody + = TRS;
});
$ ("# Producttable"). append (tbody );
// The Color of the parity line is different.
$ ("# Producttable TR: GT (0): odd"). ATTR ("class", "odd ");
$ ("# Producttable TR: GT (0): Even"). ATTR ("class", "enen ");

}
});
$ ("# Pagination"). pagination (<% = pagecount %> ,{
Callback: pageselectcallback,
Prev_text: '<previous page,
Next_text: 'Next page> ',
Items_per_page: 9,
Num_display_entries: 6,
Current_page: pageindx,
Num_edge_entries: 2
});
}
</SCRIPT>

Here it is necessary to describe the JSON data format. JSON (JavaScript Object Notation) is a lightweight data exchange format, which is similar to the XML data exchange format. The format example is as follows:Copy codeThe Code is as follows :[
{
"Term": "Bacchus ",
"Part": "N .",
"Definition": "A convenient deity specified ted by the specified ents as an excuse for getting drunk .",
"Quote ":[
"Is public worship, then, a sin .",
"That for exceptions paid to Bacchus ",
"The lictors dare to run us in .",
"And resolutely thump and whack us? "
],
"Author": "jorace"
},
{
"Term": "backbite ",
"Part": "V. T .",
"Definition": "To speak of a man as you find him when he can t find you ."
},
{
"Term": "Beard ",
"Part": "N .",
"Definition": "The hair that is commonly cut off by those who justly execrate the absurd Chinese custom of shaving the bead ."
}
]

Asp.net has a ready-made DLL processed by josn named newtonsoft. JSON. net20 (which is included at the bottom). It is very convenient to use it to process JSON. We can process JSON like an object.
Because we read a table (datatable format) from the database when reading the list, we need to display it on the front end. If We splice strings one by one, it will be very troublesome, in addition, the scalability is poor. We use JSON files to convert datatable into JSON. The method is as follows:
Code Copy code The Code is as follows: public static string datatabletojson (datatable DT, string dtname)
{
Stringbuilder sb = new stringbuilder ();
Stringwriter Sw = new stringwriter (SB );
Using (jsonwriter JW = new jsontextwriter (SW ))
{
Jsonserializer SER = new jsonserializer ();
JW. writestartobject ();
JW. writepropertyname (dtname );
JW. writestartarray ();
Foreach (datarow DR in DT. Rows)
{
JW. writestartobject ();
Foreach (datacolumn DC in DT. columns)
{
JW. writepropertyname (DC. columnname );
Ser. serialize (JW, Dr [DC]. tostring ());
}
JW. writeendobject ();
}
JW. writeendarray ();
JW. writeendobject ();
Sw. Close ();
JW. Close ();
}
Return sb. tostring ();
}

Let's take a look at the key JS Code above: initdata (pageindx) is used to process the display data on the page pageindx. Let's take a look at this Ajax processing file newshandler. ashx, of course, can also use the aspx file as the Ajax background to process files.

Add an Ajax folder in the project to store the Ajax processing files and add a generic handler type file (or a common webform) named newshandler. ashx. This file is used to process Ajax requests.

The main code is as follows:Copy codeThe Code is as follows: int pageindex; // Number of pages
Int. tryparse (context. request ["pageno"], out pageindex); // assign a value to pageindex.
String orderby = context. request ["orderby"]. tostring (); // What sort
Datatable dt = new datatable ();
Dt = pagedata (pageindex, 10, "tb_news", orderby); // get data
String jsondata = datatabletojson (DT, "news"); // create a JSON object and convert the datatable object to a JSON object
Context. response. Write (jsondata); // return JSON data

The code above contains the pagedata (pageindex, 10, "tb_news", orderby) method. The method mainly obtains the data on the page. The detailed code is as follows:
Code Copy code The Code is as follows: # region returns data of a specific page number
/// <Summary>
/// Return the data of the specified page number
/// </Summary>
/// <Param name = "pageindex"> specific page number </param>
/// <Param name = "pagesize"> page size </param>
/// <Param name = "table"> table </param>
/// <Returns> </returns>
Public datatable pagedata (INT pageindex, int pagesize, string table, string orderby)
{
String connectionstring = system. Web. configuration. webconfigurationmanager. connectionstrings ["newsconnection"]. tostring ();
Oledbconnection conn;
If (pageindex <1)
Pageindex = 1;
Conn = new oledbconnection (connectionstring );
Datatable dt = new datatable ();
Try
{
Conn. open ();
Oledbcommand distinct Total = new oledbcommand ("select count (0) from" + Table, Conn );
Int recordcount = convert. toint32 (total. executescalar (); // The total number of data
Int pagecount; // total number of pages
If (recordcount % pagesize> 0)
Pagecount = recordcount/pagesize + 1;
Else
Pagecount = recordcount/pagesize;
If (pageindex> pagecount)
Pageindex = pagecount;
Datatable datatemp = new datatable ();
String shorttext = "select news_id, news_title, news_readtimes, news_time from" + Table + "order by" + orderby + "DESC ";
Oledbcommand cmd = new oledbcommand (plain text, Conn );
Oledbdataadapter ODA = new oledbdataadapter (CMD );
ODA. Fill (datatemp );
Dt = datatemp. Clone ();
For (INT I = 0; I <pagesize; I ++)
{
If (recordcount <= (pagesize * (pageindex-1) + I ))
Break;
DT. Rows. Add (datatemp. Rows [pagesize * (pageindex-1) + I]. itemarray );
}
}
Catch (exception E)
{
}
Finally
{
Conn. Close ();
}
Return DT;
}
# Endregion

after integration, the third point of requirement analysis is realized. The above code may be a bit messy.
follow these steps:
1. Copy the corresponding JS and CSS files to the corresponding location
2. Add an Ajax file and add the newshandler. ashx file to process Ajax requests
3. In newshandler. ashx. add code to the CS file. Two methods are important: pagedata (INT pageindex, int pagesize, string table, string orderby) and ableabletojson (datatable DT, string dtname)
4. Add newshandler. ashx. the codes in Cs are well integrated with the returned JSON strings. The main code is given above. Here, pay attention to adding namespaces and adding references (for download)
5. Edit the newslist. aspx file and edit the foreground and background respectively. The front-end is used for display (provided in general, you need to combine the previous article Article ), the background mainly gets a number of news lines
the main code is as follows: copy Code the code is as follows: protected void initpagecount ()
{< br> conn = new oledbconnection (connectionstring); // create a new connection
try
{< br> Conn. open ();
string plain text = "select count (0) as pages from tb_news";
oledbcommand cmd = new oledbcommand (Te XT, Conn);
datatable dt = new datatable ();
oledbdataadapter ODA = new oledbdataadapter (CMD);
ODA. fill (DT);
If (DT! = NULL)
{< br> pagecount = DT. Rows [0] ["pages"]. tostring ();
}

}
Catch (exception E)
{
Pagecount = "0 ";
Response. Write ("error:" + E. Message); // if the connection fails, the error is displayed.
}
Finally
{
Conn. Close (); // be sure to disable Conn in time
}
}

-You need to declare protected string pagecount so that the foreground can obtain
Code attachment download: (only non-refresh pages are implemented. preview the news content and wait for the next chapter)

CSS, JS, DLL, and project (only refreshing pages)

Note: although the complete code is provided, it is not recommended to download the complete code from the very beginning.

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.