一个 Ajax和.net结合 的实例

首先我们新建一个 default.aspx 页面
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml" >
 4 <head runat="server">
 5 <title>Ajax 学习</title>
 6 <script src="SameAjax.js" type="text/javascript"></script>
 7 <style type="text/css">
 8 body
 9 {
10     font-size:12px;
11 }
12 .top 
13 {
14     position:relative;
15     float:left;
16     width:100%;
17     height:30px;
18     border-bottom:1px dotted #ccc;
19     overflow:hidden;
20 }
21 .top h3 
22 {
23     float:left;
24     color:#D55D0D;
25     font-size:14px;
26 }
27 .top .select 
28 {
29     position:absolute;
30     top:5px;
31     right:200px;
32 }
33 .top .select a 
34 {
35     text-decoration:underline;
36 }
37 
38 .top .del 
39 {
40     position:absolute;
41     top:0;
42     right:10px;
43 }
44 </style>
45 </head>
46 <body onload="Change(1,1);">
47 <form id="form1" runat="server">
48 <div class="top noBorder">
49 <h3>AJAX学习-实例</h3>
50 <div class="del">当前显示:
51 <asp:DropDownList ID="MailStatus" runat="server" onchange="Change(this.value,1);">
52 <asp:ListItem Value="" Text="全部信件"></asp:ListItem>
53 <asp:ListItem Value="0" Text="未读信件"></asp:ListItem>
54 <asp:ListItem Value="1" Text="已读信件"></asp:ListItem>
55 </asp:DropDownList>
56 </div>
57 </div>
58 <div id="MessageList" align="center"></div>
59 <table id="resultsTable" width="75%" border="0">
60 <tbody id="resultsBody">
61 </tbody>
62 </table>
63 </form>
64 </body>
65 </html>
66 


接着我们再新建一个 Js 文件
  1 // JScript 文件
  2 function CheckAll(object)  //全选
  3         {
  4             var obj =document.getElementsByName(object);
  5             for(var i=0;i<obj.length;i++)
  6                obj[i].checked= true;
  7         }
  8         
  9         function ReserveAll(object)  //反选
 10         {
 11             var obj = document.getElementsByName(object);
 12             for(var i=0;i<obj.length;i++)
 13             {
 14                 obj[i].checked = !obj[i].checked;
 15             }
 16         }
 17         
 18         
 19         
 20         /// <summary>
 21         /// 获得要删除的ID的Url
 22         /// </summary>
 23         /// <param name="object">CheckBox的name属性</param>
 24         /// <param name="ddlObject">DropDownList的ID属性</param>
 25         /// <param name="Page">当前的页码</param>
 26         function getUrl(object)
 27         {
 28             var obj = document.getElementsByName(object);
 29             var UrlParameter="";
 30             for(var i=0;i<obj.length;i++)
 31             {
 32                 if(obj[i].checked)
 33                     {
 34                         if(UrlParameter=="")
 35                         {
 36                             UrlParameter+=obj[i].value;
 37                         }
 38                         else
 39                         {
 40                            UrlParameter+="|"+obj[i].value; 
 41                         }
 42                     }
 43             }
 44             
 45             return UrlParameter;
 46         }
 47         
 48         
 49         /// <summary>
 50         /// 删除选中的记录
 51         /// </summary>
 52         /// <param name="object">CheckBox的name属性</param>
 53         /// <param name="ddlObject">DropDownList的ID属性</param>
 54         /// <param name="Page">当前的页码</param>
 55         
 56         function DelMsg(object,ddlObject,Page)
 57         {
 58             var UrlParameter =getUrl(object);
 59             if(UrlParameter!="")
 60             {
 61                 doDel(UrlParameter,ddlObject,Page);
 62                 return true;
 63             }
 64             else
 65             {
 66                 alert("请先选择一个要删除的条件");
 67                 return false;
 68             }
 69         }
 70         
 71         var xmlHttp;
 72         
 73         function createXMLHttpRequest()
 74         {
 75             if(window.ActiveXObject)
 76             {
 77                 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 78             }
 79             else if(window.XMLHttpRequest)
 80             {
 81                 xmlHttp = new XmlHttpRequest();
 82             }
 83         }
 84         
 85         function doDel(UrlParameter,Object,Page)
 86         {
 87             UrlParameter="ID="+UrlParameter;
 88             var ddlStatus = document.getElementById(Object).value;
 89             UrlParameter+="&status="+ddlStatus+"&Page="+Page;
 90             createXMLHttpRequest();
 91             var url ="DelMsg.aspx";
 92             xmlHttp.onreadystatechange = callback;
 93             xmlHttp.open("POST",url,true);
 94             xmlHttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
 95             xmlHttp.send(UrlParameter);
 96         }
 97     
 98         function Change(status,page)
 99         {   
100             createXMLHttpRequest();
101             var url ="ChangeStatus.aspx?Status="+status+"&Page="+page+"&ts="+new Date().getTime();
102             xmlHttp.open("GET",url);
103             xmlHttp.onreadystatechange = callback;
104             xmlHttp.send(null);
105         }
106         
107         function callback()
108         {
109             if(xmlHttp.readyState ==4)
110             {
111                 if(xmlHttp.status ==200)
112                 {
113                     setData(xmlHttp.responseXML);
114                 }
115                 else
116                 {
117                     document.getElementById("MessageList").innerHTML="<img src='loading.gif'>";
118                 }
119             }
120             else
121             {
122                 document.getElementById("MessageList").innerHTML="<img src='loading.gif'>";
123             }
124         }
125         
126         function setData(XmlData)
127         {   
128             var InfoNode = XmlData.getElementsByTagName("Info");        //得到Info的一个数组
129             var TotalRecord = 0,PageSize=5,CurrentPage=0;
130             
131             var HTMLINFO="";
132             HTMLINFO+="<table width='100%' border='0' cellspacing='0' cellpadding='0' class='TbMsg'>";
133             HTMLINFO+="<tr>"
134             HTMLINFO+="<th><a href='#'onClick='CheckAll(\"Message\");'>全选</a>/<a href='#'onClick='ReserveAll(\"Message\");'>反选</a></th>"
135             HTMLINFO+="<th>状态</th>"
136             HTMLINFO+="<th>主题</th>"
137             HTMLINFO+="<th>发件人</th>"
138             HTMLINFO+="<th>发送时间</th>"
139             HTMLINFO+="</tr>"
140             if(InfoNode!=null || InfoNode!="")
141             {
142                 for(var i=0;i<InfoNode.length;i++)
143                 {
144                     Infos = InfoNode[i];
145                     ID=Infos.getElementsByTagName("ID")[0].firstChild.nodeValue;
146                     Read = Infos.getElementsByTagName("Read")[0].firstChild.nodeValue;
147                     Title = Infos.getElementsByTagName("Title")[0].firstChild.nodeValue;
148                     Sender = Infos.getElementsByTagName("Sender")[0].firstChild.nodeValue;
149                     SendTime = Infos.getElementsByTagName("SendTime")[0].firstChild.nodeValue;
150                     Page=Math.ceil(Infos.getElementsByTagName("CurrentPage")[0].firstChild.nodeValue);
151                     TotalNum=Math.ceil(Infos.getElementsByTagName("TotalNum")[0].firstChild.nodeValue);
152                     HTMLINFO+="<tr>";
153                     HTMLINFO+="<td><input id='Message' type='checkbox' name='Message' value='"+ID+"' /></td>";
154                     HTMLINFO+="<td><img src='folder.jpg' alt='' /></td>";
155                     HTMLINFO+="<td class='name'><a href='?ID="+ID+"'>"+Title+"</a></td>";
156                     HTMLINFO+="<td>"+Sender+"</td>";
157                     HTMLINFO+="<td>"+SendTime+"</td>"
158                     HTMLINFO+="</tr>";
159                     CurrentPage=Page;
160                     TotalRecord=TotalNum;
161                 }
162             }
163             else
164             {
165                     HTMLINFO+="<tr>";
166                     HTMLINFO+="<td></td>";
167                     HTMLINFO+="<td></td>";
168                     HTMLINFO+="<td class='name'>没有相关数据</td>";
169                     HTMLINFO+="<td></td>";
170                     HTMLINFO+="<td></td>"
171                     HTMLINFO+="</tr>";
172             }
173            
174             HTMLINFO+="</table>";
175             HTMLINFO+="<div class='page'><div class='del'>";
176             HTMLINFO+="<input id='btnDel' type='submit' value='删除' onclick='return DelMsg(\"Message\",\"MailStatus\","+CurrentPage+");' /></div>";
177             
178             var ddlStatus = document.getElementById("MailStatus").value;
179             if(ddlStatus=="")
180                 ddlStatus=-1;
181                 
182             var PageCount = Math.ceil(TotalRecord / PageSize);
183             var PrePage =(CurrentPage-1)<=1?1:(CurrentPage-1);
184             var NextPage =(CurrentPage+1)<=PageCount?(CurrentPage+1):PageCount;
185             
186             if(PageCount>1)
187             {
188                 HTMLINFO+="<a href='JavaScript:Change("+ddlStatus+","+PrePage+")'>上一页</a> ";
189                 
190                 for(var i=1;i<=PageCount;i++)
191                 {
192                     if(CurrentPage==i)
193                         HTMLINFO+=" <b>"+i+"</b> ";
194                     else
195                         HTMLINFO+=" <a href='JavaScript:Change("+ddlStatus+","+i+");'> "+i+"</a> ";
196                 }
197                 
198                 HTMLINFO+=" <a href='JavaScript:Change("+ddlStatus+","+NextPage+")'>下一页</a> "
199              }  
200             
201             HTMLINFO+="共有"+TotalRecord+"个记录,每页"+PageSize+"个,一共有"+PageCount+"页</div>";
202             
203             document.getElementById("MessageList").innerHTML=HTMLINFO;
204         }
205 
206 

再建立两个处理ajax发送过来条件的页面
新建一个ChangeStauts.aspx页面,把前台页面中除了第一行外全部删除,后台页面如下:
这个是xml版本的,所以不要求数据库,只要是为了大家能不操作数据库的条件下就使用这个例子

 1 using System;
 2 using System.Data;
 3 using System.Configuration;
 4 using System.Collections;
 5 using System.Web;
 6 using System.Web.Security;
 7 using System.Web.UI;
 8 using System.Web.UI.WebControls;
 9 using System.Web.UI.WebControls.WebParts;
10 using System.Web.UI.HtmlControls;
11 
12 public partial class ChangeStatus : System.Web.UI.Page
13 {
14     protected void Page_Load(object sender, EventArgs e)
15     {
16         string Status = "";
17         try
18         {
19             Status = Request["Status"];
20             if (Status == "-1")
21                 Status = "";
22         }
23         catch
24         {
25 
26             Status = "";
27         }
28         string Page = "";
29         try
30         {
31             Page = Request["Page"];
32         }
33         catch
34         {
35             Page = "1";
36         }
37         int CurrentPage = Convert.ToInt32(Page);
38         
39         Response.ContentType = "text/xml";
40         int PageSize = 5;
41         string Result = "";
42 
43         for (int i = (CurrentPage - 1* PageSize+1; i <= (CurrentPage * PageSize); i++)
44         {
45             Result += "<Info>";
46             Result += "<ID>" + i + "</ID>";
47             Result += "<Read>" + i % 2 + "</Read>";
48             Result += "<Title>信息的标题" + i + "</Title>";
49             Result += "<Sender>作者" + i + "</Sender>";
50             Result += "<SendTime>2007-08-" + i + "</SendTime>";
51             Result += "<CurrentPage>" + CurrentPage + "</CurrentPage>";
52             Result += "<TotalNum>20</TotalNum>";
53             Result += "</Info>";
54 
55         }
56         Response.Write("<Message>" + Result + "</Message>");
57     }
58 }

最后我们要建立一个为“删除”按钮做后续操作的页面

我们新建文件叫 DelMsg.aspx ,它的后台页面为数据库版本的,至于数据库怎么设计,我想大家如果能看到这里的话,也应该知道怎么设计的


  1 using System;
  2 using System.Data;
  3 using System.Configuration;
  4 using System.Collections;
  5 using System.Web;
  6 using System.Web.Security;
  7 using System.Web.UI;
  8 using System.Web.UI.WebControls;
  9 using System.Web.UI.WebControls.WebParts;
 10 using System.Web.UI.HtmlControls;
 11 
 12 public partial class DelMsg : System.Web.UI.Page
 13 {
 14 
 15     protected void Page_Load(object sender, EventArgs e)
 16     {
 17 
 18         ////本页是数据库版本的,其它的一些方法就不写出来了,应该也没有什么难度的
 19         string IDList = "", Status = "", Page = "";
 20 
 21         try
 22         {
 23             IDList = Request["ID"].ToString();
 24         }
 25         catch
 26         {
 27             IDList = "";
 28         }
 29 
 30         try
 31         {
 32             Status = Request["Status"];
 33             if (Status == "-1")
 34                 Status = "";
 35         }
 36         catch
 37         {
 38             Status = "";
 39         }
 40 
 41         try
 42         {
 43             Page = Request["Page"];
 44         }
 45         catch
 46         {
 47             Page = "1";
 48         }
 49         int CurrentPage = Convert.ToInt32(Page);
 50 
 51         string IDList = "('" + ID.Replace("|""','"+ "')";
 52 
 53         string SQL = "";
 54 
 55         //先删除记录
 56         SQL = "Delete from T_Message where F_ID in " + IDList;
 57         Database.ExecuteNonQuery(CommandType.Text, SQL);
 58 
 59         //得到删除记录后,数据库中还有的记录总数
 60         string SQL2 = "select count(F_ID) AS TotalRecord from V_Message where F_UserID='" + Profile.UserSystem.UserId + "' and F_isRead='" + Status + "'";
 61         if (Status != "")
 62         {
 63             SQL2 += " and F_isRead='" + Status + "'";
 64         }
 65         int TotalNum = (int)Database.ExecuteScalar(CommandType.Text, SQL2);
 66 
 67         //把删除记录后的内容从数据库中读出来,假设每页的数据是12条
 68         SQL = "select  top 12 * from V_Message where F_UserID='" + Profile.UserSystem.UserId + "' and  F_ID not in (Select top " + (CurrentPage - 1* 12 + " F_ID from V_Message where F_UserID='" + Profile.UserSystem.UserId + "'";
 69 
 70         if (Status != "")
 71         {
 72             SQL += " and F_isRead='" + Status + "'";
 73         }
 74 
 75         SQL += " ORDER BY F_InputDate DESC )";
 76 
 77         if (Status != "")
 78         {
 79             SQL += " and F_isRead='" + Status + "'";
 80         }
 81         SQL += " ORDER BY F_InputDate DESC";
 82 
 83         SqlDataReader sdr = Database.ExecuteReader(CommandType.Text, SQL);
 84         Response.ContentType = "text/xml";
 85         string Result = "";
 86         while (sdr.Read())
 87         {
 88             Result += "<Info>";
 89             Result += "<ID>" + sdr["F_ID"].ToString() + "</ID>";
 90             Result += "<Read>" + sdr["F_IsRead"].ToString() + "</Read>";
 91             Result += "<Title>" + sdr["F_Title"].ToString() + "</Title>";
 92             Result += "<Sender>" + sdr["UserName"].ToString() + "</Sender>";
 93             Result += "<SendTime>" + Convert.ToDateTime(sdr["F_InputDate"].ToString()).ToShortDateString() + "</SendTime>";
 94             Result += "<CurrentPage>" + CurrentPage + "</CurrentPage>";
 95             Result += "<TotalNum>+TotalNum+</TotalNum>";
 96             Result += "</Info>";
 97         }
 98         Response.Write("<Message>" + Result + "</Message>");
 99     }
100 }


posted @ 2007-09-04 23:16  海底的鱼  阅读(582)  评论(2)    收藏  举报