Step by step to create a beautiful news list (no refresh paging, Content Preview) Chapter III _ Basic Application

Source: Internet
Author: User
Tags foreach
Let's take a look at the requirements analysis:

3.== read the news list without a refresh, click on the next page to trigger the event, invoke Ajax to find the next page of data in the database and return it, and then display it on the page.

Here are two events, are JS events, we use jquery code to achieve.

pagination, we use jquery paging plug-in pagination, the official address for the http://plugins.jquery.com/project/pagination download JS files and CSS files (the download address below)

Let's talk about its basic usage:

Like a typical jquery plugin, this plugin is easy to use. The method is pagination, such as $ ("#page"). Pagination (100), where the 100 parameters are required to indicate the total number of items displayed, which is the simplest use.

For example, use the following code:
Copy Code code as follows:

$ ("#Pagination"). Pagination (56, {
Num_edge_entries:2,
Num_display_entries:4,
Callback:pageselectcallback,
Items_per_page:1
});

The meaning of this code is: a total of 2 (maxentries) list items, the end of both sides of the page is displayed at the end of the num_edge_entries, the number of consecutive page bodies show 4 (num_display_entries), The callback function is Pageselectcallback (callback), and the list item displayed on each page is 1 (items_per_page). You can modify the parameters in this configuration against the parameter table.

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

Then tell me how to integrate it into our side.

Add relevant JS files and CSS files to the newslist.aspx page (download address below): Jquery-1.4.1.js,pagination.js
Copy Code code 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>

Then, let's look at the key JS code:
Copy Code code as follows:

<script type= "Text/javascript" language= "JavaScript" >
$ (). Ready (function () {
InitData (0);
});
Process Paging
function Pageselectcallback (page_id, JQ) {
alert (page_id);
InitData (page_id);
};
function InitData (PAGEINDX)
{
var tbody = "";
var orderby= "news_id";
$.ajax ({
Type: "POST",//Post mode transmission
DataType: "JSON",//Data format JSON
URL: ' ajax/newshandler.ashx ',//Destination 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 &GT;&LT;TD style= ' text-align:center ' > ' + n.news_time + ' </td></tr> ';
Tbody + = TRS;
});
$ ("#productTable"). Append (tbody);
Odd and even rows with different colors
$ ("#productTable tr:gt (0): Odd"). attr ("Class", "odd");
$ ("#productTable tr:gt (0): Even"). attr ("Class", "Enen");

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

There is a need to explain the JSON data format, JSON (JavaScript Object notation) is a lightweight data interchange format, which is similar to the XML Data Interchange format, as shown in the following format:
Copy Code code as follows:

[
{
"term": "BACCHUS",
"Part": "N.",
"Definition": "A convenient deity invented by the ancients as a excuse for getting.",
"Quote": [
"Is public worship,then,a sin.",
"That's for devotions 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 the A man as your find him when he can t find you."
},
{
"term": "BEARD",
"Part": "N.",
"Definition": "The Hair," "commonly", "" "is those", "" execrate "absurd" justly Chinese ."
}
]

ASP.net has a ready-made DLL for JOSN processing, named Newtonsoft.Json.Net20 (the download address below), which is handy for processing JSON, and we can process JSON as we do with objects.
Because when we read the list from the database is a table (DataTable format), and to show it in the foreground, if you put together a string of words will be very cumbersome, and poor scalability, all we use the JSON file, This requires a way to convert the DataTable to JSON, as follows:
Code
Copy Code code 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 of page PAGEINDX, Let's take a look at this Ajax processing file Newshandler.ashx, of course, you can also use ASPX files as Ajax background processing files.

Add Ajax folders to the project to store Ajax processing files, and add generic handler type files (or generic WebForm), named Newshandler.ashx, which is used to handle AJAX requests.

The main code is as follows:
Copy Code code as follows:

int pageindex;//Pages
Int. TryParse (context. request["PageNo"], out pageindex);//Assign value to pageindex
string by = = Context. Request["by"]. ToString ();//What sort
DataTable dt = new DataTable ();
DT = Pagedata (pageindex, "Tb_news", by);//Get Data
String jsondata = Datatabletojson (dt, News);//Create a JSON object to convert a DataTable object to a JSON object
Context. Response.Write (Jsondata);//Return JSON data

The above code has such a method Pagedata (pageindex, ten, "Tb_news", by); Method mainly obtains the first few pages of data, the detailed code is as follows:
Code
Copy Code code as follows:

#region return data of a specific number of pages
<summary>
Returns data for a specific number of pages
</summary>
<param name= "pageindex" > specific page </param>
<param name= "pagesize" > Page size </param>
<param name= "table" > which table </param>
<returns></returns>
Public DataTable pagedata (int pageindex, int pagesize, string table, string by)
{
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 cmdtotal = new OleDbCommand ("SELECT count (0) from" + table, conn);
int recordCount = Convert.ToInt32 (Cmdtotal.executescalar ());//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 cmdtext = "Select News_id,news_title,news_readtimes,news_time from" + table + ' ORDER BY ' + order + "desc";
OleDbCommand cmd = new OleDbCommand (CMDTEXT, 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


Integration will achieve the 3rd requirement analysis. Maybe the code above is a little bit messy.
Follow the steps below:
1. Copy the corresponding JS file and CSS file to the corresponding location
2. Add Ajax files and add newshandler.ashx files to handle AJAX requests
3. Adding code to the NewsHandler.ashx.cs file has two methods that are important, pagedata (int pageindex, int pagesize, string table, string by) and Datatabletojson (DataTable dt, string dtname)
4. Combine the processing code in the NewsHandler.ashx.cs with the returned JSON string, the main code is given above, note here to add namespaces and add references (provide downloads).
5. Edit the Newslist.aspx file and edit the foreground and background separately. Foreground to display (has been generally given, need to combine the previous article), the background mainly to get a news bar number
The main code is as follows:
Copy Code code as follows:

protected void Initpagecount ()
{
conn = new OleDbConnection (connectionString);
Try
{
Conn. Open ();
String cmdtext = "SELECT count (0) as pages from Tb_news";
OleDbCommand cmd = new OleDbCommand (CMDTEXT, conn);
DataTable dt = new DataTable ();
OleDbDataAdapter ODA = new OleDbDataAdapter (cmd);
Oda. Fill (DT);
if (dt!= null)
{
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 turn off Conn in time.
}
}

Required-Need to declare protected string PageCount so that the foreground can get
Attached code Download: (only to achieve the no refresh of the pagination, preview the news content waiting for the next chapter)

CSS, JS, DLL, project (no refresh paging only)

Note: Although the complete code is provided, it is not recommended to download the complete at the beginning, to do it yourself

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.