使用 PageRequestManager 事件
更新:2007 年 11 月
Microsoft AJAX Library 中的 PageRequestManager 類別會與具備 AJAX 能力之 ASP.NET Web 網頁上的 ScriptManager 和 UpdatePanel 伺服器控制項協調一致以啟用網頁局部更新。PageRequestManager 類別會公開方法、屬性和事件,讓頁面項目執行非同步回傳時,用戶端程式設計變得較為容易。例如,PageRequestManager 類別可讓您處理用戶端頁面生命週期內的事件,並提供專用於網頁局部更新的自訂事件處理常式。
若要在用戶端指令碼中使用 PageRequestManager 類別,您必須在 Web 網頁上放置 ScriptManager 伺服器控制項。ScriptManager 控制項的 EnablePartialRendering 屬性必須設定為 true (即預設值)。當 EnablePartialRendering 設定為 true 時,就能在頁面中使用包含 PageRequestManager 類別的用戶端指令碼程式庫。
取得 PageRequestManager 類別的執行個體
每個頁面都有一個 PageRequestManager 執行個體。您不需要建立類別的執行個體,而是藉由呼叫 getInstance 方法來取得對目前執行個體的參考,如下列範例所示:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
當您取得 PageRequestManager 類別的目前執行個體時,您就能存取其所有方法、屬性和事件。例如,您可以取得 isInAsyncPostBack 屬性來判斷是否正在進行非同步回傳,如下列範例所示:
function InitializeRequest(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'CancelPostBack') {
prm.abortPostBack();
}
}
function InitializeRequest(sender, args)
{
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm.get_isInAsyncPostBack() & args.get_postBackElement().id == 'CancelPostBack') {
prm.abortPostBack();
}
}
如果 ScriptManager 控制項的 EnablePartialRendering 屬性為 false,您就無法存取 isInAsyncPostBack 屬性,因為並沒有任何 PageRequestManager 執行個體。
用戶端頁面生命週期事件
在瀏覽器的一般頁面處理期間,window.onload DOM 事件會在第一次載入頁面時引發。同樣地,當頁面重新整理或使用者離開頁面時,會引發 window.onunload DOM 事件。
但是,在非同步回傳期間並不會引發這些事件。為協助您管理非同步回傳的這些事件類型,PageRequestManager 類別會公開一組事件。這些事件與 window.load 和其他 DOM 事件類似,但也會在非同步回傳期間發生。對於每個非同步回傳,都會引發 PageRequestManager 類別中的所有頁面事件,並呼叫任何附加的事件處理常式。
注意事項: |
---|
對於同步回傳只會引發 pageLoaded 事件。 |
您可以撰寫用戶端指令碼來處理由 PageRequestManager 類別引發的事件。不同的事件引數物件會傳遞給不同事件的處理常式。下表總結了 PageRequestManager 類別事件與對應的事件引數類別。表格中的事件順序便是單一非同步回傳在沒有發生錯誤時的事件順序。
initializeRequest
初始化非同步回傳的要求之前引發。事件資料會以 InitializeRequestEventArgs 物件型式傳遞給處理常式。該物件讓引發回傳及後續要求物件的項目變成可供使用。beginRequest
在非同步回傳傳送至伺服器之前引發。事件資料會傳遞給處理常式以做為 BeginRequestEventArgs 物件。該物件可讓導致回傳及基礎要求物件的項目變成可供使用。pageLoading
收到對最近一次非同步回傳的回應之後、但尚未更新頁面之前引發。事件資料會傳遞給處理常式以做為 PageLoadingEventArgs 物件。該物件提供可用的相關資訊,說明哪些面板將因最近一次非同步回傳而導致刪除或更新。pageLoaded
最近一次回傳後更新頁面區域之後引發。事件資料會傳遞給處理常式做為 PageLoadedEventArgs 物件。該物件提供相關資訊說明哪些面板已經建立及更新。對於同步回傳,只會建立面板,但對非同步回傳則會同時建立及更新面板。endRequest
完成要求處理時引發。事件資料會傳遞給處理常式做為 EndRequestEventArgs 物件。該物件提供已發生的錯誤及該錯誤是否已處理的相關資訊。它也使回應物件變成可供使用。
如果您使用 ScriptManager 控制項的 RegisterDataItem 方法,在非同步回傳期間傳送額外資料,您就能從 PageLoadingEventArgs、PageLoadedEventArgs 和 EndRequestEventArgs 物件中存取該資料。
事件順序會因各種狀況而有所不同。上表順序只適用於成功的單一非同步回傳。其他狀況包括下列各項:
多個回傳,其中最近的回傳具有較高的優先順序,這是預設行為。只會引發最近一次非同步回傳的事件。
多個回傳,其中某回傳具有較高優先順序,在完成它之前會取消所有後續回傳。只會引發已取消回傳的 initializeRequest 事件。
已停止的非同步回傳。視停止回傳的時間而定,可能不會引發某些事件。
頁面的初始要求 (HTTP GET) 或頁面重新整理。在第一次載入頁面或在瀏覽器中重新整理頁面時,只會引發 pageLoaded 事件。
停止及取消非同步回傳
兩種常見的工作便是停止正在進行的非同步回傳,以及在開始處理之前取消新的要求。若要執行這些工作,請執行下列動作:
若要停止現有的非同步回傳,您可以呼叫 PageRequestManager 類別的 abortPostback 方法。
若要取消新的非同步回傳,您可以處理 PageRequestManager 類別的 initializeRequest 事件,並將 cancel 屬性設定為 true。
停止非同步回傳
下列範例顯示如何停止非同步回傳。initializeRequest 事件處理常式指令碼會檢查使用者是否已選擇停止回傳。如果是,程式碼便會呼叫 abortPostback 方法。
<%@ Page Language="VB" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
Protected Sub NewsClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
System.Threading.Thread.Sleep(2000)
HeadlineList.DataSource = GetHeadlines()
HeadlineList.DataBind()
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If Not (IsPostBack) Then
HeadlineList.DataSource = GetHeadlines()
HeadlineList.DataBind()
End If
End Sub
' Helper method to simulate news headline fetch.
Private Function GetHeadlines() As SortedList
Dim headlines As New SortedList()
headlines.Add(1, "This is headline 1.")
headlines.Add(2, "This is headline 2.")
headlines.Add(3, "This is headline 3.")
headlines.Add(4, "This is headline 4.")
headlines.Add(5, "This is headline 5.")
headlines.Add(6, "(Last updated on " & DateTime.Now.ToString() & ")")
Return headlines
End Function
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title>Canceling Postback Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
#UpdatePanel1{
width: 400px;
height: 200px;
border: solid 1px gray;
}
div.AlertStyle {
font-size: smaller;
background-color: #FFC080;
width: 400px;
height: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<form id="form1" >
<div >
<asp:ScriptManager ID="ScriptManager1" >
<Scripts>
<asp:ScriptReference Path="CancelPostback.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="Server" >
<ContentTemplate>
<asp:DataList ID="HeadlineList" >
<HeaderTemplate>
<strong>Headlines</strong>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Value") %>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
<FooterStyle HorizontalAlign="right" />
</asp:DataList>
<p style="text-align:right">
<asp:Button ID="RefreshButton"
Text="Refresh"
OnClick="NewsClick_Handler" />
</p>
<div id="AlertDiv" class="AlertStyle">
<span id="AlertMessage"></span>
<asp:LinkButton ID="CancelRefresh" >
Cancel</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
protected void NewsClick_Handler(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
HeadlineList.DataSource = GetHeadlines();
HeadlineList.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HeadlineList.DataSource = GetHeadlines();
HeadlineList.DataBind();
}
}
// Helper method to simulate news headline fetch.
private SortedList GetHeadlines()
{
SortedList headlines = new SortedList();
headlines.Add(1, "This is headline 1.");
headlines.Add(2, "This is headline 2.");
headlines.Add(3, "This is headline 3.");
headlines.Add(4, "This is headline 4.");
headlines.Add(5, "This is headline 5.");
headlines.Add(6, "(Last updated on " + DateTime.Now.ToString() + ")");
return headlines;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>Canceling Postback Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
#UpdatePanel1{
width: 400px;
height: 200px;
border: solid 1px gray;
}
div.AlertStyle {
font-size: smaller;
background-color: #FFC080;
width: 400px;
height: 20px;
visibility: hidden;
}
</style>
</head>
<body>
<form id="form1" >
<div >
<asp:ScriptManager ID="ScriptManager1" >
<Scripts>
<asp:ScriptReference Path="CancelPostback.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="Server" >
<ContentTemplate>
<asp:DataList ID="HeadlineList" >
<HeaderTemplate>
<strong>Headlines</strong>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Value") %>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
<FooterStyle HorizontalAlign="right" />
</asp:DataList>
<p style="text-align:right">
<asp:Button ID="RefreshButton"
Text="Refresh"
OnClick="NewsClick_Handler" />
</p>
<div id="AlertDiv" class="AlertStyle">
<span id="AlertMessage"></span>
<asp:LinkButton ID="CancelRefresh" >
Cancel</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
如需詳細資訊,請參閱取消非同步回傳。
取消新的非同步回傳
下列範例顯示如何指定特定非同步回傳的優先順序。在完成目前的非同步回傳之前,這會取消所有後續的非同步回傳 (依照預設,最近一次非同步回傳具有最高優先順序)。initializeRequest 事件處理常式會檢查頁面上具有較高優先順序的項目是否已初始化非同步回傳。如果是,就會設定 InitializeRequestEventArgs 物件的 cancel 屬性,以取消所有後續回傳。InitializeRequestEventArgs 事件繼承自 CancelEventArgs 類別,該類別已定義了 cancel 屬性。
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Threading.Thread.Sleep(4000)
Label1.Text = "Last update from server " & DateTime.Now.ToString()
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Threading.Thread.Sleep(1000)
Label2.Text = "Last update from server " & DateTime.Now.ToString()
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title>Postback Precedence Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
#UpdatePanel1, #UpdatePanel2 {
width: 400px;
height: 100px;
border: solid 1px gray;
}
div.MessageStyle {
background-color: #FFC080;
top: 95%;
left: 1%;
height: 20px;
width: 600px;
position: absolute;
visibility: hidden;
}
</style>
</head>
<body>
<form id="form1" >
<div>
<asp:ScriptManager ID="ScriptManager1" >
<Scripts>
<asp:ScriptReference Path="PostBackPrecedence.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="Server" >
<ContentTemplate>
<strong>UpdatePanel 1</strong><br />
This postback takes precedence.<br />
<asp:Label ID="Label1" >Panel initially rendered.</asp:Label><br />
<asp:Button ID="Button1" Text="Button" OnClick="Button1_Click" />
<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
Panel1 updating...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="Server" >
<ContentTemplate>
<strong>UpdatePanel 2</strong><br />
<asp:Label ID="Label2" >Panel initially rendered.</asp:Label><br />
<asp:Button ID="Button2" Text="Button" OnClick="Button2_Click" />
<asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel2">
<ProgressTemplate>
Panel2 updating...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
<div id="AlertDiv" class="MessageStyle">
<span id="AlertMessage"></span>
</div>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
Label1.Text = "Last update from server " + DateTime.Now.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(1000);
Label2.Text = "Last update from server " + DateTime.Now.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title>Postback Precedence Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
#UpdatePanel1, #UpdatePanel2 {
width: 400px;
height: 100px;
border: solid 1px gray;
}
div.MessageStyle {
background-color: #FFC080;
top: 95%;
left: 1%;
height: 20px;
width: 600px;
position: absolute;
visibility: hidden;
}
</style>
</head>
<body>
<form id="form1" >
<div>
<asp:ScriptManager ID="ScriptManager1" >
<Scripts>
<asp:ScriptReference Path="PostBackPrecedence.js" />
</Scripts>
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="Server" >
<ContentTemplate>
<strong>UpdatePanel 1</strong><br />
This postback takes precedence.<br />
<asp:Label ID="Label1" >Panel initially rendered.</asp:Label><br />
<asp:Button ID="Button1" Text="Button" OnClick="Button1_Click" />
<asp:UpdateProgress ID="UpdateProgress1" AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>
Panel1 updating...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" UpdateMode="Conditional" runat="Server" >
<ContentTemplate>
<strong>UpdatePanel 2</strong><br />
<asp:Label ID="Label2" >Panel initially rendered.</asp:Label><br />
<asp:Button ID="Button2" Text="Button" OnClick="Button2_Click" />
<asp:UpdateProgress ID="UpdateProgress2" AssociatedUpdatePanelID="UpdatePanel2">
<ProgressTemplate>
Panel2 updating...
</ProgressTemplate>
</asp:UpdateProgress>
</ContentTemplate>
</asp:UpdatePanel>
<div id="AlertDiv" class="MessageStyle">
<span id="AlertMessage"></span>
</div>
</div>
</form>
</body>
</html>
如需詳細資訊,請參閱指定特定非同步回傳的優先順序。
顯示自訂錯誤訊息
下列範例顯示如何在非同步回傳期間發生錯誤時顯示自訂的錯誤訊息。ScriptManager 控制項的 AsyncPostBackError 事件會在伺服端程式碼中予以處理,並將錯誤相關資訊傳送至瀏覽器以便顯示。
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
Protected Sub ErrorProcessClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
'This handler demonstrates an error condition. In this example
' the server error gets intercepted on the client and an alert is shown.
Dim exc As New ArgumentException()
exc.Data("GUID") = Guid.NewGuid().ToString().Replace("-"," - ")
Throw exc
End Sub
Protected Sub SuccessProcessClick_Handler(ByVal sender As Object, ByVal e As EventArgs)
'This handler demonstrates no server side exception.
UpdatePanelMessage.Text = "The asynchronous postback completed successfully."
End Sub
Protected Sub ScriptManager1_AsyncPostBackError(ByVal sender As Object, ByVal e As System.Web.UI.AsyncPostBackErrorEventArgs)
If Not (e.Exception.Data("GUID") Is Nothing) Then
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message & _
" When reporting this error use the following ID: " & _
e.Exception.Data("GUID").ToString()
Else
ScriptManager1.AsyncPostBackErrorMessage = _
"The server could not process the request."
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>PageRequestManager endRequestEventArgs Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
#AlertDiv{
left: 40%; top: 40%;
position: absolute; width: 200px;
padding: 12px;
border: #000000 1px solid;
background-color: white;
text-align: left;
visibility: hidden;
z-index: 99;
}
#AlertButtons{
position: absolute;
right: 5%;
bottom: 5%;
}
</style>
</head>
<body id="bodytag">
<form id="form1" >
<div>
<asp:ScriptManager ID="ScriptManager1"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
/>
<script type="text/javascript" language="javascript">
var divElem = 'AlertDiv';
var messageElem = 'AlertMessage';
var bodyTag = 'bodytag';
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function ToggleAlertDiv(visString)
{
if (visString == 'hidden')
{
$get(bodyTag).style.backgroundColor = 'white';
}
else
{
$get(bodyTag).style.backgroundColor = 'gray';
}
var adiv = $get(divElem);
adiv.style.visibility = visString;
}
function ClearErrorState() {
$get(messageElem).innerHTML = '';
ToggleAlertDiv('hidden');
}
function EndRequestHandler(sender, args)
{
if (args.get_error() != undefined)
{
var errorMessage = args.get_error().message;
args.set_errorHandled(true);
ToggleAlertDiv('visible');
$get(messageElem).innerHTML = errorMessage;
}
}
</script>
<asp:UpdatePanel runat="Server" UpdateMode="Conditional" ID="UpdatePanel1">
<ContentTemplate>
<asp:Panel ID="Panel1" GroupingText="Update Panel">
<asp:Label ID="UpdatePanelMessage" />
<br />
Last update:
<%= DateTime.Now.ToString() %>
.
<br />
<asp:Button ID="Button1" Text="Submit Successful Async Postback"
OnClick="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
<asp:Button ID="Button2" Text="Submit Async Postback With Error"
OnClick="ErrorProcessClick_Handler" OnClientClick="ClearErrorState()" />
<br />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<div id="AlertDiv">
<div id="AlertMessage">
</div>
<br />
<div id="AlertButtons" >
<input id="OKButton" type="button" value="OK"
onclick="ClearErrorState()" />
</div>
</div>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
protected void ErrorProcessClick_Handler(object sender, EventArgs e)
{
// This handler demonstrates an error condition. In this example
// the server error gets intercepted on the client and an alert is shown.
Exception exc = new ArgumentException();
exc.Data["GUID"] = Guid.NewGuid().ToString().Replace("-"," - ");
throw exc;
}
protected void SuccessProcessClick_Handler(object sender, EventArgs e)
{
// This handler demonstrates no server side exception.
UpdatePanelMessage.Text = "The asynchronous postback completed successfully.";
}
protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
{
if (e.Exception.Data["GUID"] != null)
{
ScriptManager1.AsyncPostBackErrorMessage = e.Exception.Message +
" When reporting this error use the following ID: " +
e.Exception.Data["GUID"].ToString();
}
else
{
ScriptManager1.AsyncPostBackErrorMessage =
"The server could not process the request.";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head >
<title>PageRequestManager endRequestEventArgs Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
#AlertDiv{
left: 40%; top: 40%;
position: absolute; width: 200px;
padding: 12px;
border: #000000 1px solid;
background-color: white;
text-align: left;
visibility: hidden;
z-index: 99;
}
#AlertButtons{
position: absolute;
right: 5%;
bottom: 5%;
}
</style>
</head>
<body id="bodytag">
<form id="form1" >
<div>
<asp:ScriptManager ID="ScriptManager1"
OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
/>
<script type="text/javascript" language="javascript">
var divElem = 'AlertDiv';
var messageElem = 'AlertMessage';
var bodyTag = 'bodytag';
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function ToggleAlertDiv(visString)
{
if (visString == 'hidden')
{
$get(bodyTag).style.backgroundColor = 'white';
}
else
{
$get(bodyTag).style.backgroundColor = 'gray';
}
var adiv = $get(divElem);
adiv.style.visibility = visString;
}
function ClearErrorState() {
$get(messageElem).innerHTML = '';
ToggleAlertDiv('hidden');
}
function EndRequestHandler(sender, args)
{
if (args.get_error() != undefined)
{
var errorMessage = args.get_error().message;
args.set_errorHandled(true);
ToggleAlertDiv('visible');
$get(messageElem).innerHTML = errorMessage;
}
}
</script>
<asp:UpdatePanel runat="Server" UpdateMode="Conditional" ID="UpdatePanel1">
<ContentTemplate>
<asp:Panel ID="Panel1" GroupingText="Update Panel">
<asp:Label ID="UpdatePanelMessage" />
<br />
Last update:
<%= DateTime.Now.ToString() %>
.
<br />
<asp:Button ID="Button1" Text="Submit Successful Async Postback"
OnClick="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
<asp:Button ID="Button2" Text="Submit Async Postback With Error"
OnClick="ErrorProcessClick_Handler" OnClientClick="ClearErrorState()" />
<br />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
<div id="AlertDiv">
<div id="AlertMessage">
</div>
<br />
<div id="AlertButtons" >
<input id="OKButton" type="button" value="OK"
onclick="ClearErrorState()" />
</div>
</div>
</div>
</form>
</body>
</html>
如需詳細資訊,請參閱自訂 ASP.NET UpdatePanel 控制項的錯誤處理。
建立面板的動畫
下列範例顯示如何建立 UpdatePanel 控制項的動畫,以通知使用者該內容已經變更。當您按一下 LinkButton 控制項時,UpdatePanel 控制項四周的框線會短暫顯示。
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
Protected Sub ChosenDate_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim dt As New DateTime()
DateTime.TryParse(ChosenDate.Text, dt)
CalendarPicker.SelectedDate = dt
CalendarPicker.VisibleDate = dt
End Sub
Protected Sub Close_Click(ByVal sender As Object, ByVal e As EventArgs)
SetDateSelectionAndVisible()
End Sub
Protected Sub ShowDatePickerPopOut_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
DatePickerPopOut.Visible = Not (DatePickerPopOut.Visible)
End Sub
Protected Sub CalendarPicker_SelectionChanged(ByVal sender As Object, ByVal e As EventArgs)
SetDateSelectionAndVisible()
End Sub
Private Sub SetDateSelectionAndVisible()
If (CalendarPicker.SelectedDates.Count <> 0) Then
ChosenDate.Text = CalendarPicker.SelectedDate.ToShortDateString()
End If
DatePickerPopOut.Visible = False
End Sub
Protected Sub SubmitButton_Click(ByVal sender As Object, ByVal e As EventArgs)
If (Page.IsValid) Then
MessageLabel.Text = "An email with availability was sent."
Else
MessageLabel.Text = ""
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
CompareValidatorDate.ValueToCompare = DateTime.Today.ToShortDateString()
ExtraShow1.Text = DateTime.Today.AddDays(10.0).ToShortDateString()
ExtraShow2.Text = DateTime.Today.AddDays(11.0).ToShortDateString()
End Sub
Protected Sub ExtraShow_Click(ByVal sender As Object, ByVal e As EventArgs)
ChosenDate.Text = CType(sender, LinkButton).Text
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title>Calendar Popup Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
.PopUpCalendarStyle
{
background-color:lightblue;
position:absolute;
visibility:show;
margin: 15px 0px 0px 10px;
z-index:99;
border: solid 2px black;
}
.UpdatePanelContainer
{
width: 260px;
height:110px;
}
</style>
</head>
<body>
<form id="form1" >
<asp:ScriptManager ID="ScriptManager1" />
<script type="text/javascript">
Type.registerNamespace("ScriptLibrary");
ScriptLibrary.BorderAnimation = function(color, duration) {
this._color = color;
this._duration = duration;
}
ScriptLibrary.BorderAnimation.prototype = {
animatePanel: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '1px';
s.borderColor = this._color;
s.borderStyle = 'solid';
window.setTimeout(
function() {{ s.borderWidth = 0; }},
this._duration
);
}
}
ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);
var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 1000);
var postbackElement;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
function beginRequest(sender, args) {
postbackElement = args.get_postBackElement();
}
function pageLoaded(sender, args) {
var updatedPanels = args.get_panelsUpdated();
if (typeof(postbackElement) === "undefined") {
return;
}
else if (postbackElement.id.toLowerCase().indexOf('extrashow') > -1) {
for (i=0; i < updatedPanels.length; i++) {
panelUpdatedAnimation.animatePanel(updatedPanels[i]);
}
}
}
</script>
<h1>Tickets</h1>
<p>
<strong>Latest News</strong> Due to overwhelming response, we
have added two extra shows on:
<asp:LinkButton ID="ExtraShow1" OnClick="ExtraShow_Click" />
and
<asp:LinkButton ID="ExtraShow2" OnClick="ExtraShow_Click" />.
Don't forget curtain time is at 7:00pm sharp. No late arrivals.
</p>
<hr />
<div class="UpdatePanelContainer">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
<asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
</Triggers>
<ContentTemplate>
<fieldset >
<legend>Check Ticket Availability</legend>Date
<asp:TextBox ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
<asp:ImageButton ID="ShowDatePickerPopOut" OnClick="ShowDatePickerPopOut_Click"
ImageUrl="../images/calendar.gif" AlternateText="Choose a date."
Height="20px" Width="20px" />
<asp:Panel ID="DatePickerPopOut" CssClass="PopUpCalendarStyle"
Visible="false" >
<asp:Calendar ID="CalendarPicker" OnSelectionChanged="CalendarPicker_SelectionChanged">
</asp:Calendar>
<br />
<asp:LinkButton ID="CloseDatePickerPopOut" Font-Size="small"
OnClick="Close_Click" ToolTip="Close Pop out">
Close
</asp:LinkButton>
</asp:Panel>
<br />
Email
<asp:TextBox ID="EmailTextBox" />
<br />
<br />
<asp:Button ID="SubmitButton" Text="Check" ValidationGroup="RequiredFields"
OnClick="SubmitButton_Click" />
<br />
<asp:CompareValidator ID="CompareValidatorDate"
ControlToValidate="ChosenDate" ErrorMessage="Choose a date in the future."
Operator="GreaterThanEqual" Type="Date" Display="None" ValidationGroup="RequiredFields" EnableClientScript="False"></asp:CompareValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorDate"
ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
ControlToValidate="EmailTextBox" Display="None"
ValidationGroup="RequiredFields" ErrorMessage="The email was not correctly formatted."
ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" EnableClientScript="False"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
<asp:ValidationSummary ID="ValidationSummary1"
ValidationGroup="RequiredFields" EnableClientScript="False" />
<asp:Label ID="MessageLabel" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script >
protected void ChosenDate_TextChanged(object sender, EventArgs e)
{
DateTime dt = new DateTime();
DateTime.TryParse(ChosenDate.Text, out dt);
CalendarPicker.SelectedDate = dt;
CalendarPicker.VisibleDate = dt;
}
protected void Close_Click(object sender, EventArgs e)
{
SetDateSelectionAndVisible();
}
protected void ShowDatePickerPopOut_Click(object sender, ImageClickEventArgs e)
{
DatePickerPopOut.Visible = !DatePickerPopOut.Visible;
}
protected void CalendarPicker_SelectionChanged(object sender, EventArgs e)
{
SetDateSelectionAndVisible();
}
private void SetDateSelectionAndVisible()
{
if (CalendarPicker.SelectedDates.Count != 0)
ChosenDate.Text = CalendarPicker.SelectedDate.ToShortDateString();
DatePickerPopOut.Visible = false;
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
MessageLabel.Text = "An email with availability was sent.";
}
else
{
MessageLabel.Text = "";
}
}
protected void Page_Load(object sender, EventArgs e)
{
CompareValidatorDate.ValueToCompare = DateTime.Today.ToShortDateString();
ExtraShow1.Text = DateTime.Today.AddDays(10.0).ToShortDateString();
ExtraShow2.Text = DateTime.Today.AddDays(11.0).ToShortDateString();
}
protected void ExtraShow_Click(object sender, EventArgs e)
{
ChosenDate.Text = ((LinkButton)sender).Text;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >
<title>Calendar Popup Example</title>
<style type="text/css">
body {
font-family: Tahoma;
}
.PopUpCalendarStyle
{
background-color:lightblue;
position:absolute;
visibility:show;
margin: 15px 0px 0px 10px;
z-index:99;
border: solid 2px black;
}
.UpdatePanelContainer
{
width: 260px;
height:110px;
}
</style>
</head>
<body>
<form id="form1" >
<asp:ScriptManager ID="ScriptManager1" />
<script type="text/javascript">
Type.registerNamespace("ScriptLibrary");
ScriptLibrary.BorderAnimation = function(color, duration) {
this._color = color;
this._duration = duration;
}
ScriptLibrary.BorderAnimation.prototype = {
animatePanel: function(panelElement) {
var s = panelElement.style;
s.borderWidth = '1px';
s.borderColor = this._color;
s.borderStyle = 'solid';
window.setTimeout(
function() {{ s.borderWidth = 0; }},
this._duration
);
}
}
ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);
var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 1000);
var postbackElement;
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
function beginRequest(sender, args) {
postbackElement = args.get_postBackElement();
}
function pageLoaded(sender, args) {
var updatedPanels = args.get_panelsUpdated();
if (typeof(postbackElement) === "undefined") {
return;
}
else if (postbackElement.id.toLowerCase().indexOf('extrashow') > -1) {
for (i=0; i < updatedPanels.length; i++) {
panelUpdatedAnimation.animatePanel(updatedPanels[i]);
}
}
}
</script>
<h1>Tickets</h1>
<p>
<strong>Latest News</strong> Due to overwhelming response, we
have added two extra shows on:
<asp:LinkButton ID="ExtraShow1" OnClick="ExtraShow_Click" />
and
<asp:LinkButton ID="ExtraShow2" OnClick="ExtraShow_Click" />.
Don't forget curtain time is at 7:00pm sharp. No late arrivals.
</p>
<hr />
<div class="UpdatePanelContainer">
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
<asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
</Triggers>
<ContentTemplate>
<fieldset>
<legend>Check Ticket Availability</legend>Date
<asp:TextBox ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
<asp:ImageButton ID="ShowDatePickerPopOut" OnClick="ShowDatePickerPopOut_Click"
ImageUrl="../images/calendar.gif" AlternateText="Choose a date."
Height="20px" Width="20px" />
<asp:Panel ID="DatePickerPopOut" CssClass="PopUpCalendarStyle"
Visible="false" >
<asp:Calendar ID="CalendarPicker" OnSelectionChanged="CalendarPicker_SelectionChanged">
</asp:Calendar>
<br />
<asp:LinkButton ID="CloseDatePickerPopOut" Font-Size="small"
OnClick="Close_Click" ToolTip="Close Pop out">
Close
</asp:LinkButton>
</asp:Panel>
<br />
Email
<asp:TextBox ID="EmailTextBox" />
<br />
<br />
<asp:Button ID="SubmitButton" Text="Check" ValidationGroup="RequiredFields"
OnClick="SubmitButton_Click" />
<br />
<asp:CompareValidator ID="CompareValidatorDate"
ControlToValidate="ChosenDate" ErrorMessage="Choose a date in the future."
Operator="GreaterThanEqual" Type="Date" Display="None" ValidationGroup="RequiredFields" EnableClientScript="False"></asp:CompareValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorDate"
ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
ControlToValidate="EmailTextBox" Display="None"
ValidationGroup="RequiredFields" ErrorMessage="The email was not correctly formatted."
ValidationExpression="^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$" EnableClientScript="False"></asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
<asp:ValidationSummary ID="ValidationSummary1"
ValidationGroup="RequiredFields" EnableClientScript="False" />
<asp:Label ID="MessageLabel" />
</fieldset>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
如需詳細資訊,請參閱逐步解說:建立 ASP.NET UpdatePanel 控制項動畫。