利用Client端的Javascript來Cancel ASP.NET AJAX 非同步更新

利用Client端的Javascript來Cancel ASP.NET AJAX 非同步更新

最近在一本書上看到如何cancel正在做非同步更新的ajax

小弟以一個範例實作分享給大家呀....

c#範例..

環境:Visual Studio 2008 + .Net Framework 3.5

CancelUpdate.aspx

01 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CancelUpdate.aspx.cs" Inherits="CancelUpdate" %>
02
03 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 <html xmlns="http://www.w3.org/1999/xhtml">
05 <head id="Head1" runat="server">
06     <title>CancelRefresh</title>
07 </head>
08 <body>
09     <form id="form1" runat="server">
10         <div>
11             <asp:ScriptManager ID="ScriptManager1" runat="server">
12             </asp:ScriptManager>
13         </div>
14         <asp:UpdatePanel ID="UpdatePanel1" runat="server">
15             <contenttemplate>
16 <asp:Button ID="Button1" runat="server" Text="Refresh"
17 onclick="Button1_Click" />
18 <br />
19 <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
20 </contenttemplate>
21             <triggers>
22 <asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
23 </triggers>
24         </asp:UpdatePanel>
25         <asp:UpdateProgress ID="UpdateProgress1" runat="server" AssociatedUpdatePanelID="UpdatePanel1">
26             <progresstemplate>
27 Loading...<br />
28 <asp:Button ID="Button2" runat="server" Text="Cancel Refresh" OnClientClick="AbortPostBack(); return false;" />
29 </progresstemplate>
30         </asp:UpdateProgress>
31     </form>
32
33     <script type="text/javascript">
34
35 var prm = Sys.WebForms.PageRequestManager.getInstance();
36
37 function AbortPostBack()
38 {
39 if (prm.get_isInAsyncPostBack())
40 {
41 prm.abortPostBack();
42 }
43 }
44
45     </script>
46
47 </body>
48 </html>
49


CancelUpdate.aspx.cs

01 using System;
02 using System.Collections;
03 using System.Configuration;
04 using System.Data;
05 using System.Linq;
06 using System.Web;
07 using System.Web.Security;
08 using System.Web.UI;
09 using System.Web.UI.HtmlControls;
10 using System.Web.UI.WebControls;
11 using System.Web.UI.WebControls.WebParts;
12 using System.Xml.Linq;

13
14 public partial class CancelUpdate : System.Web.UI.Page
15 {
16     protected void Page_Load(object sender, EventArgs e)
17     {
18
19     }

20     protected void Button1_Click(object sender, EventArgs e)
21     {
22         //Sleep 5 Seconds
23         System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));
24
25         //show time
26         this.Label1.Text = DateTime.Now.ToLongTimeString();
27     }

28 }


執行結果: