asp.net USES Jquery+Ajax+Json to achieve no page refresh instance code
- 2020-11-18 06:09:33
- OfStack
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxJson.aspx.cs" Inherits="AjaxJson" %>
<!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 runat="server">
<title>Jquery+Ajax+Json paging </title>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<link href="Styles/tablecloth.css" rel="stylesheet" type="text/css" />
<link href="Styles/pagination.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="Scripts/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.pagination.js"></script>
<script type="text/javascript">
var pageIndex = 0; // Page index initial value
var pageSize = 10; // Initialize the number of display bars per page, modify the number of display bars, you can modify here
$(function () {
InitTable(0); //Load Event that initializes the table data and indexes the page as 0 (the first 1 Page)
// Paging, PageCount Is the total number of entries, which is a required parameter, and all other parameters are optional
$("#Pagination").pagination(<%=pageCount %>, {
callback: PageCallback,
prev_text: ' on 1 page ', // on 1 In the page button text
next_text: ' Under the 1 page ', // Under the 1 In the page button text
items_per_page: pageSize, // Article according to the number of
num_display_entries: 6, // Number of page entries in the body of consecutive pages
current_page: pageIndex, // Current page index
num_edge_entries: 2 // The number of pagination entries on both sides
});
// Page calls
function PageCallback(index, jq) {
InitTable(index);
}
// The request data
function InitTable(pageIndex) {
$.ajax({
type: "POST",
dataType: "json",
url: 'SupplyAJAX.aspx', // Submitted to the 1 General handlers request data
data: "type=show&random=" + Math.random() + "&pageIndex=" + (pageIndex + 1) + "&pageSize=" + pageSize, // Submit two parameters: pageIndex( Page index ) . pageSize( Article according to the number of )
error: function () { alert('error data'); }, // Error execution method
success: function (data) {
$("#Result tr:gt(0)").remove(); // remove Id for Result The rows in the table from no 2 Line start (here depending on the page layout)
var json = data; // An array of
var html = "";
$.each(json.data, function (index, item) {
// Loop fetch data
var id = item.Id;
var name = item.Name;
var sex = item.Sex;
html += "<tr><td>" + id + "</td><td>" + name + "</td><td>" + sex + "</td></tr>";
});
$("#Result").append(html); // Appends the returned data to the table
}
});
}
});
</script>
</head>
<body>
<form id="form1" runat="server">
<table id="Result" cellspacing="0" cellpadding="0">
<tr>
<th>
Serial number
</th>
<th>
The name
</th>
<th>
gender
</th>
</tr>
</table>
<div id="Pagination">
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class AjaxJson : System.Web.UI.Page
{
public string pageCount = string.Empty; // The total number of entries
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string url = "/SupplyAJAX.aspx";
string strResult = GetRequestJsonString(url, "type=getcount");
pageCount = strResult.ToString();
}
}
#region The background for ashx Data returned
/// <summary>
/// The background for ashx Data returned
/// </summary>
/// <param name="relativePath"> address </param>
/// <param name="data"> parameter </param>
/// <returns></returns>
public static string GetRequestJsonString(string relativePath, string data)
{
string requestUrl = GetRequestUrl(relativePath, data);
try
{
WebRequest request = WebRequest.Create(requestUrl);
request.Method = "GET";
StreamReader jsonStream = new StreamReader(request.GetResponse().GetResponseStream());
string jsonObject = jsonStream.ReadToEnd();
return jsonObject;
}
catch
{
return string.Empty;
}
}
public static string GetRequestUrl(string relativePath, string data)
{
string absolutePath = HttpContext.Current.Request.Url.AbsoluteUri;
string hostNameAndPort = HttpContext.Current.Request.Url.Authority;
string applicationDir = HttpContext.Current.Request.ApplicationPath;
StringBuilder sbRequestUrl = new StringBuilder();
sbRequestUrl.Append(absolutePath.Substring(0, absolutePath.IndexOf(hostNameAndPort)));
sbRequestUrl.Append(hostNameAndPort);
sbRequestUrl.Append(applicationDir);
sbRequestUrl.Append(relativePath);
if (!string.IsNullOrEmpty(data))
{
sbRequestUrl.Append("?");
sbRequestUrl.Append(data);
}
return sbRequestUrl.ToString();
}
#endregion
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
// new
using System.Web.Script.Serialization;
using System.Text;
public partial class SupplyAJAX : System.Web.UI.Page
{
protected static List<Student> StudentList = new List<Student>();
protected static int RecordCount = 0;
protected static DataTable dt = CreateDT();
protected void Page_Load(object sender, EventArgs e)
{
switch (Request["type"])
{
case "show":
#region Paging configuration
// The exact number of pages
int pageIndex;
int.TryParse(Request["pageIndex"], out pageIndex);
// The number of pages displayed
int PageSize = Convert.ToInt32(Request["pageSize"]);
if (pageIndex == 0)
{
pageIndex = 1;
}
#endregion
DataTable PagedDT = GetPagedTable(dt, pageIndex, PageSize);
List<Student> list = new List<Student>();
foreach (DataRow dr in PagedDT.Rows)
{
Student c = new Student();
c.Id = (Int32)dr["Id"];
c.Name = dr["Name"].ToString();
c.Sex = dr["Sex"].ToString();
list.Add(c);
}
string json = new JavaScriptSerializer().Serialize(list);// This is critical, otherwise error
StringBuilder Builder = new StringBuilder();
Builder.Append("{");
Builder.Append("\"recordcount\":" + RecordCount + ",");
Builder.Append("\"data\":");
Builder.Append(json);
Builder.Append("}");
Response.ContentType = "application/json";
Response.Write(Builder.ToString());
break;
case "getcount":
Response.Write(dt.Rows.Count);
break;
case "add":
break;
case "update":
break;
case "delete":
break;
}
Response.End();
}
#region Simulated data
private static DataTable CreateDT()
{
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("Id", typeof(int)) { DefaultValue = 0 });
dt.Columns.Add(new DataColumn("Name", typeof(string)) { DefaultValue = "1" });
dt.Columns.Add(new DataColumn("Sex", typeof(string)) { DefaultValue = " male " });
for (int i = 1; i <= 1000; i++)
{
dt.Rows.Add(i, " zhang 3" + i.ToString().PadLeft(4, '0'));
}
RecordCount = dt.Rows.Count;
return dt;
}
#endregion
/// <summary>
/// right DataTable paging , The start page for 1
/// </summary>
/// <param name="dt"></param>
/// <param name="PageIndex"></param>
/// <param name="PageSize"></param>
/// <returns></returns>
public static DataTable GetPagedTable(DataTable dt, int PageIndex, int PageSize)
{
if (PageIndex == 0)
return dt;
DataTable newdt = dt.Copy();
newdt.Clear();
int rowbegin = (PageIndex - 1) * PageSize;
int rowend = PageIndex * PageSize;
if (rowbegin >= dt.Rows.Count)
return newdt;
if (rowend > dt.Rows.Count)
rowend = dt.Rows.Count;
for (int i = rowbegin; i <= rowend - 1; i++)
{
DataRow newdr = newdt.NewRow();
DataRow dr = dt.Rows[i];
foreach (DataColumn column in dt.Columns)
{
newdr[column.ColumnName] = dr[column.ColumnName];
}
newdt.Rows.Add(newdr);
}
return newdt;
}
/// <summary>
/// Get total pages
/// </summary>
/// <param name="sumCount"> Number of result sets </param>
/// <param name="pageSize"> The page number </param>
/// <returns></returns>
public static int getPageCount(int sumCount, int pageSize)
{
int page = sumCount / pageSize;
if (sumCount % pageSize > 0)
{
page = page + 1;
}
return page;
}
public struct Student
{
public int Id;
public string Name;
public string Sex;
}
}