处理 PageRequestManager 事件

更新:2007 年 11 月

Microsoft AJAX Library 中的 PageRequestManager 类可与支持 AJAX 的 ASP.NET 网页上的 ScriptManagerUpdatePanel 服务器控件协调使用,从而启用部分页更新。当页元素执行异步回发时,PageRequestManager 类可公开方法、属性和事件,从而使客户端编程变得更容易。例如,PageRequestManager 类可使您能在客户端页生命周期内处理事件,并可使您能提供特定于部分页更新的自定义事件处理程序。

若要在客户端脚本中使用 PageRequestManager 类,则必须在网页中放入一个 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 类中的所有页事件,并会调用所有附加的事件处理程序。

Bb398976.alert_note(zh-cn,VS.90).gif说明:

对于同步回发,则仅引发 pageLoaded 事件。

您可以编写客户端脚本来处理 PageRequestManager 类引发的事件。对于不同事件的处理程序,传递不同的事件参数对象。下表汇总出了 PageRequestManager 类事件及相应的事件参数类。表中事件的顺序与未发生错误的单个异步回发的事件顺序相同。

  • initializeRequest
    引发于为异步回发初始化请求之前。事件数据将作为 InitializeRequestEventArgs 对象传递到处理程序。该对象可提供导致回发的元素和基础请求对象。

  • beginRequest
    引发于马上要向服务器发送异步回发之前。事件数据将作为 BeginRequestEventArgs 对象传递到处理程序。该对象可提供导致回发的元素和基础请求对象。

  • pageLoading
    引发于收到对最新异步回发的响应之后、对页进行任何更新之前。事件数据将作为 PageLoadingEventArgs 对象传递到处理程序。该对象可提供作为最新异步回发的结果的、有关将要删除和更新的面板的信息。

  • pageLoaded
    引发于在最新回发发生后执行了页区域更新以后。事件数据将作为 PageLoadedEventArgs 对象传递到处理程序。该对象可提供已创建或更新的面板的相关信息。对于同步回发,仅可以创建面板;而对于异步回发,则不但可以创建面板,而且还可以更新面板。

  • endRequest
    引发于请求处理完成以后。事件数据将作为 EndRequestEventArgs 对象传递到处理程序。该对象可提供已发生的错误以及是否已处理了错误的相关信息,它还可提供响应对象。

如果在异步回发过程中,使用 ScriptManager 控件的 RegisterDataItem 方法来发送额外数据,则您可以通过 PageLoadingEventArgsPageLoadedEventArgsEndRequestEventArgs 对象访问该数据。

具体情况不同,则事件的顺序也会不同。上表中的顺序是单个成功的异步回发的顺序。其他情况如下:

  • 有多个回发,最新回发具有优先权,这是默认行为。仅引发最新异步回发的事件。

  • 有多个回发,给予其中一个回发优先权,这将会不断地取消后续回发,直至获得优先权的回发完成为止。仅会为取消了的回发引发 initializeRequest 事件。

  • 停止了异步回发。可能不会引发某些事件,具体取决于停止回发的时间。

  • 页的初始请求 (HTTP GET) 或页刷新。在浏览器中第一次加载页或刷新页面时,仅引发 pageLoaded 事件。

停止和取消异步回发

有两个常规任务可停止正在进行的异步回发,并可在新请求开始之前取消该请求。若要执行这些任务,您需要执行以下操作:

  • 若要停止现有异步回发,则需要调用 PageRequestManager 类的 abortPostback 方法。

  • 若要取消新的异步回发,则需要处理 PageRequestManager 类的initializeRequest 事件,并需要将“取消”属性设置为 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 runat="server">
    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" runat="server">
    <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" runat="server">
        <div >
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
        <asp:ScriptReference Path="CancelPostback.js" />
        </Scripts>
        </asp:ScriptManager>
        <asp:UpdatePanel  ID="UpdatePanel1" runat="Server" >
            <ContentTemplate>
                <asp:DataList ID="HeadlineList" runat="server">
                    <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" 
                            runat="server" 
                            OnClick="NewsClick_Handler" />
                </p>
                <div id="AlertDiv" class="AlertStyle">
                <span id="AlertMessage"></span> 
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:LinkButton ID="CancelRefresh" runat="server">
                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 runat="server">
    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 runat="server">
    <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" runat="server">
        <div >
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Scripts>
        <asp:ScriptReference Path="CancelPostback.js" />
        </Scripts>
        </asp:ScriptManager>
        <asp:UpdatePanel  ID="UpdatePanel1" runat="Server" >
            <ContentTemplate>
                <asp:DataList ID="HeadlineList" runat="server">
                    <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" 
                            runat="server" 
                            OnClick="NewsClick_Handler" />
                </p>
                <div id="AlertDiv" class="AlertStyle">
                <span id="AlertMessage"></span> 
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:LinkButton ID="CancelRefresh" runat="server">
                Cancel</asp:LinkButton>                      
            </ContentTemplate>
        </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

有关更多信息,请参见取消异步回发

取消新的异步回发

下面的示例演示如何向特定异步回发授予优先权。这将不断取消后续异步回发,直至当前回发完成为止。(默认情况下,最新异步回发将获得优先权。) initializeRequest 事件处理程序可检查异步回发是否是由页面中具有优先权的元素启动的。如果是由具有优先权的元素启动的,则会通过设置 InitializeRequestEventArgs 对象的 cancel 属性取消所有后续回发。InitializeRequestEventArgs 事件是从定义了 cancel 属性的 CancelEventArgs 类继承的。

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    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" runat="server">
    <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" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <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" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />&nbsp;
                <asp:UpdateProgress ID="UpdateProgress1" runat="server" 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" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
                <asp:UpdateProgress ID="UpdateProgress2" runat="server" 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 runat="server">
    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" runat="server">
    <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" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" runat="server">
            <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" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />&nbsp;
                <asp:UpdateProgress ID="UpdateProgress1" runat="server" 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" runat="server">Panel initially rendered.</asp:Label><br />
                <asp:Button ID="Button2" runat="server" Text="Button" OnClick="Button2_Click" />
                <asp:UpdateProgress ID="UpdateProgress2" runat="server" 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 runat="server">

    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 runat="server">
    <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" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" 
                               OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
                               runat="server" />

            <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" runat="server" GroupingText="Update Panel">
                        <asp:Label ID="UpdatePanelMessage" runat="server" />
                        <br />
                        Last update:
                        <%= DateTime.Now.ToString() %>
                        .
                        <br />
                        <asp:Button runat="server" ID="Button1" Text="Submit Successful Async Postback"
                            OnClick="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
                        <asp:Button runat="server" 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" 
                           runat="server" 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 runat="server">

    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 runat="server">
    <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" runat="server">
        <div>
            <asp:ScriptManager ID="ScriptManager1" 
                               OnAsyncPostBackError="ScriptManager1_AsyncPostBackError"
                               runat="server" />

            <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" runat="server" GroupingText="Update Panel">
                        <asp:Label ID="UpdatePanelMessage" runat="server" />
                        <br />
                        Last update:
                        <%= DateTime.Now.ToString() %>
                        .
                        <br />
                        <asp:Button runat="server" ID="Button1" Text="Submit Successful Async Postback"
                            OnClick="SuccessProcessClick_Handler" OnClientClick="ClearErrorState()" />
                        <asp:Button runat="server" 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" 
                           runat="server" 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 runat="server">
    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" runat="server">
    <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" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <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" runat="server" OnClick="ExtraShow_Click" />
            and
            <asp:LinkButton ID="ExtraShow2" runat="server" OnClick="ExtraShow_Click" />.
            Don't forget curtain time is at 7:00pm sharp. No late arrivals.
        </p>
        <hr />
        <div class="UpdatePanelContainer">
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
                </Triggers>
                <ContentTemplate>
                    <fieldset >
                        <legend>Check Ticket Availability</legend>Date
                        <asp:TextBox runat="server" ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
                        <asp:ImageButton runat="server" 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" runat="server">
                            <asp:Calendar ID="CalendarPicker" runat="server" OnSelectionChanged="CalendarPicker_SelectionChanged">
                            </asp:Calendar>
                            <br />
                            <asp:LinkButton ID="CloseDatePickerPopOut" runat="server" Font-Size="small"
                                OnClick="Close_Click" ToolTip="Close Pop out">
                            Close
                            </asp:LinkButton>
                        </asp:Panel>
                        <br />
                        Email
                        <asp:TextBox runat="server" ID="EmailTextBox" />
                        <br />
                        <br />
                        <asp:Button ID="SubmitButton" Text="Check" runat="server" ValidationGroup="RequiredFields"
                            OnClick="SubmitButton_Click" />
                        <br />
                        <asp:CompareValidator ID="CompareValidatorDate" runat="server"
                            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" runat="server"
                            ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
                            ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                            runat="server" 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"
                            runat="server" ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
                            Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ValidationGroup="RequiredFields" EnableClientScript="False" />
                        <asp:Label ID="MessageLabel" runat="server" />
                    </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 runat="server">
    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" runat="server">
    <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" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <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" runat="server" OnClick="ExtraShow_Click" />
            and
            <asp:LinkButton ID="ExtraShow2" runat="server" OnClick="ExtraShow_Click" />.
            Don't forget curtain time is at 7:00pm sharp. No late arrivals.
        </p>
        <hr />
        <div class="UpdatePanelContainer">
            <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
                <Triggers>
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow1" />
                    <asp:AsyncPostBackTrigger ControlID="ExtraShow2" />
                </Triggers>
                <ContentTemplate>
                    <fieldset>
                        <legend>Check Ticket Availability</legend>Date
                        <asp:TextBox runat="server" ID="ChosenDate" OnTextChanged="ChosenDate_TextChanged" />
                        <asp:ImageButton runat="server" 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" runat="server">
                            <asp:Calendar ID="CalendarPicker" runat="server" OnSelectionChanged="CalendarPicker_SelectionChanged">
                            </asp:Calendar>
                            <br />
                            <asp:LinkButton ID="CloseDatePickerPopOut" runat="server" Font-Size="small"
                                OnClick="Close_Click" ToolTip="Close Pop out">
                            Close
                            </asp:LinkButton>
                        </asp:Panel>
                        <br />
                        Email
                        <asp:TextBox runat="server" ID="EmailTextBox" />
                        <br />
                        <br />
                        <asp:Button ID="SubmitButton" Text="Check" runat="server" ValidationGroup="RequiredFields"
                            OnClick="SubmitButton_Click" />
                        <br />
                        <asp:CompareValidator ID="CompareValidatorDate" runat="server"
                            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" runat="server"
                            ControlToValidate="ChosenDate" Display="None" ErrorMessage="Date is required."
                            ValidationGroup="RequiredFields" EnableClientScript="False"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                            runat="server" 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"
                            runat="server" ValidationGroup="RequiredFields" ControlToValidate="EmailTextBox"
                            Display="None" ErrorMessage="Email is required." EnableClientScript="False"></asp:RequiredFieldValidator><br />
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ValidationGroup="RequiredFields" EnableClientScript="False" />
                        <asp:Label ID="MessageLabel" runat="server" />
                    </fieldset>
                </ContentTemplate>
            </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

有关更多信息,请参见演练:对 ASP.NET UpdatePanel 控件进行动画处理

请参见

概念

ASP.NET PageRequestManager 类概述