Trabalhando com eventos PageRequestManager

A classe PageRequestManager na caixa Microsoft AJAX Library coordena com os controles de servidor ScriptManager e UpdatePanel em um página da Web com AJAX ativado do ASP.NET para ativar a atualização da página parcial.A classe PageRequestManager expõe métodos, propriedades e eventos para tornar a programação cliente mais fácil quando os elementos da página estiverem realizando postagens assíncronas.Por exemplo, a classe PageRequestManager permite que você manipule eventos no ciclo de vida da página cliente e fornecer os manipuladores de eventos personalizados que são específicos para atualizações parcial de página.

Para usar a classe PageRequestManager em script de cliente, você deve colocar um controle de servidor ScriptManager na página da Web.A propriedade EnablePartialRendering do controle ScriptManager deve ser definida como true (que é o padrão).Quando EnablePartialRendering é definida como true, a biblioteca de script cliente que contém a classe PageRequestManager estará disponível na página.

Obtendo uma Instância da Classe PageRequestManager

Há uma instância PageRequestManager por página.Você não cria uma instância da classe.Em vez disso, você obtém uma referência à instância atual chamando o método getInstance, conforme mostrado no exemplo o seguir:

Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(InitializeRequest);

Quando você tem a instância atual da classe PageRequestManager, você pode acessar todos os seus métodos, propriedades e eventos.Por exemplo, você pode obter a propriedade isInAsyncPostBack para determinar se uma postagem assíncrona está em andamento, conforme mostrado no exemplo o seguir:

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();
    }    
}

Se a propriedade EnablePartialRendering do controle ScriptManager for false, você não poderá acessar a propriedade isInAsyncPostBack porque não há nenhuma instância PageRequestManager.

Eventos no Ciclo de Vida da Página Cliente

Durante processamento ordinário de página no navegador, o evento DOM window.onload é gerado quando a página for carregada pela primeira vez.Da mesma forma, o evento DOM window.onunload é gerado quando a página é atualizada ou quando o usuário sai da página.

No entanto, esses eventos não são gerados durante postagens assíncronas.Para ajudá-lo a gerenciar esses tipos de eventos de postagens assíncronas, a classe PageRequestManager expõe um conjunto de eventos.Eles se parecem com window.load e outros eventos DOM, mas eles também ocorrem durante postagens assíncronas.Para cada postagem assíncrona, todos os eventos da página na classe PageRequestManager são gerados e são chamados os manipuladores de evento anexados.

Observação:

Para postagens síncronas, apenas o evento pageLoaded é gerado.

Você pode escrever script de cliente para manipular eventos gerados pela classe PageRequestManager.Diferentes objetos argumentos de eventos são passados para manipuladores por eventos diferentes.A tabela a seguir resume os eventos da classe PageRequestManagere as classes de argumentos de eventos correspondentes.A ordem dos eventos na tabela é a ordem dos eventos para uma única postagem assíncrona sem erros.

  • initializeRequest
    Gerado antes de solicitação é inicializado para uma postagem assíncrona.Dados do evento são passados para manipuladores como um objeto InitializeRequestEventArgs.O objeto torna disponível o elemento que causou a postagem e o objeto de solicitação subjacente.

  • beginRequest
    Gerado logo antes da postagem assíncrona ser enviada ao servidor.Dados do evento são passados para manipuladores como um objeto BeginRequestEventArgs.O objeto torna disponível o elemento que causou a postagem e o objeto de solicitação subjacente.

  • pageLoading
    Gerado após a resposta para a postagem assíncrona mais recente ser recebida, mas antes que quaisquer atualizações para a página tenham sido feitas.Dados do evento são passados para manipuladores como um objeto PageLoadingEventArgs.O objeto torna informações disponíveis sobre quais painéis serão excluídos e atualizados como um resultado da postagem assíncrona mais recente.

  • pageLoaded
    Lançado após regiões da página terem sido atualizadas após a postagem mais recente.Dados do evento são passados para manipuladores como um objeto PageLoadingEventArgs.O objeto torna informações disponíveis sobre quais painéis foram criados ou atualizados.Para postagens síncronas, painéis só podem ser criados, mas para postagens assíncronas, painéis podem ser tanto criados como atualizados.

  • endRequest
    Gerado quando o processamento de solicitação estiver concluído.Dados do evento são passados para manipuladores como um objeto EndRequestEventArgs.O objeto torna informações disponíveis sobre os erros que ocorreram e se o erro foi tratado.Ele também torna disponível o objeto de resposta.

Se você usar o método RegisterDataItem do controle ScriptManager para enviar dados adicionais durante uma postagem assíncrona, você pode acessar os dados dos objetos PageLoadingEventArgs,PageLoadedEventArgs e EndRequestEventArgs.

A sequência de eventos varia de acordo com os diferentes cenários.A ordem na tabela anterior é para uma única e bem-sucedida postagem assíncrona.Outras situações incluem o seguinte:

  • Várias postagens onde a postagem mais recente tem precedência, que é o comportamento padrão.Somente eventos para a postagem assíncrona mais recentes são gerados.

  • Várias postagens onde uma postagem tem precedência, o que cancela todas as postagens subsequentes até que ela seja concluída.Somente o evento initializeRequest é gerado para postagens canceladas.

  • Uma postagem assíncrona que foi parada.Dependendo de quando a postagem for interrompida, alguns eventos podem não ser gerados.

  • Uma requisição inicial (HTTP GET) de uma página, ou uma atualização de página.Quando uma página é carregada pela primeira vez ou quando ele é atualizado no navegador, apenas o evento pageLoaded é gerado.

Parando e Cancelando Postagens Assíncronas

Duas tarefas comuns são a interrupção de uma postagem assíncrona que está em andamento e o cancelamento de uma nova solicitação antes de ela ter sido iniciada.Para executar essas tarefas, faça o seguinte:

  • Para interromper uma postagem assíncrona existente, chame o método abortPostback da classe PageRequestManager.

  • Para cancelar uma nova postagem assíncrona, manipule o evento initializeRequest da classe PageRequestManager e defina a propriedade Cancelar para true.

Interrompendo uma Postagem Assíncrona

O exemplo a seguir mostra como interromper uma postagem assíncrona.O script manipulador de eventos initializeRequest verifica se o usuário escolheu parar a postagem.Nesse caso, o código chama o método 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> 
                &nbsp;&nbsp;&nbsp;&nbsp;
                <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> 
                &nbsp;&nbsp;&nbsp;&nbsp;
                <asp:LinkButton ID="CancelRefresh" >
                Cancel</asp:LinkButton>                      
            </ContentTemplate>
        </asp:UpdatePanel>
        </div>
    </form>
</body>
</html>

Para obter mais informações, consulte Cancelando um Postback Assíncrono.

Cancelando Novas Postagens Assíncronas

O exemplo a seguir mostra como dar prioridade a uma postagem assíncrona específica.Esse procedimento cancela todas as postagens assíncronas subsequentes até que aquela atual seja concluída.(Por padrão, a postagem assíncrona mais recente tem precedência.) O manipulador de eventos initializeRequest verifica se a postagem assíncrona foi iniciada por um elemento na página que tem precedência.Nesse caso, todas as postagens subsequentes serão canceladas, definindo a propriedade cancel do objeto InitializeRequestEventArgs.O evento InitializeRequestEventArgs herda da classe CancelEventArgs, onde a propriedade cancel está definida.

<%@ 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" />&nbsp;
                <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" />&nbsp;
                <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>

Para obter mais informações, consulte Fornecer precedência para um postback assíncrono específico.

Exibindo uma Mensagem de Erro Personalizada

O exemplo a seguir mostra como exibir um mensagem de erro personalizada quando ocorrer um erro durante uma postagem assíncrona.O evento AsyncPostBackError do controle ScriptManager é tratado no código do servidor, e as informações sobre o erro são enviadas ao navegador para serem exibidas.

<%@ 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>

Para obter mais informações, consulte Personalizando a Manipulação de Erro para o Controle UpdatePanel do ASP.NET.

Animando Painéis

O exemplo a seguir mostra como animar um controle UpdatePanel para notificar o usuário que o conteúdo foi alterado.Quando você clica no controle LinkButton, uma borda ao redor do controle UpdatePanel é mostrada rapidamente.

<%@ 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>

Para obter mais informações, consulte Demonstra Passo a passo: Animar controles UpdatePanel do ASP.NET.

Consulte também

Conceitos

Visão geral da classe ASP.NET PageRequestManager