Utilisation d'événements PageRequestManager

Mise à jour : novembre 2007

La classe PageRequestManager s'accorde Microsoft AJAX Library avec les contrôles serveur ScriptManager et UpdatePanel sur une page Web ASP.NET AJAX pour activer la mise à jour de page partielle. La classe PageRequestManager expose des méthodes, des propriétés et des événements pour simplifier la programmation cliente lorsque les éléments de page exécutent des publications (postback) asynchrones. Par exemple, la classe PageRequestManager vous permet de gérer des événements dans le cycle de vie de la page client et de fournir des gestionnaires d'événements personnalisés qui sont spécifiques aux mises à jour de pages partielles.

Pour utiliser la classe PageRequestManager dans le script client, vous devez mettre un contrôle serveur ScriptManager sur la page Web. La propriété EnablePartialRendering du contrôle ScriptManager doit avoir la valeur true (qui est la valeur par défaut). Lorsque EnablePartialRendering a la valeur true, la bibliothèque de scripts client qui contient la classe PageRequestManager est disponible dans la page.

Obtention d'une instance de la classe PageRequestManager

Il y a une instance PageRequestManager par page. Ne créez pas une instance de la classe. À la place, vous obtenez la référence de l'instance actuelle en appelant la méthode getInstance, comme illustré dans l'exemple suivant :

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

Lorsque vous avez l'instance actuelle de la classe PageRequestManager, vous pouvez accéder à toutes ses méthodes, propriétés et événements. Par exemple, vous pouvez obtenir la propriété isInAsyncPostBack pour déterminer si une publication asynchrone est en cours, comme illustré dans l'exemple suivant :

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

Si la propriété EnablePartialRendering du contrôle ScriptManager est false, vous ne pouvez pas accéder la propriété isInAsyncPostBack parce que n'est pas une instance PageRequestManager.

Événements de cycle de vie de la page client

Pendant le traitement ordinaire de la page dans le navigateur, l'événement DOM window.onload est déclenché lors du chargement initial de la page. De même, l'événement DOM window.onunload est déclenché lorsque la page est actualisée ou lorsque l'utilisateur se déplace hors de la page.

Toutefois, ces événements ne sont pas déclenchés lors des publications asynchrones. Pour vous aider à gérer ces types d'événements lors des publications asynchrones, la classe PageRequestManager expose un jeu d'événements. Ils ressemblent aux événements window.load et autres événements DOM, mais ils surviennent également pendant les publications asynchrones. Pour chaque publication asynchrone, tous les événements de page dans la classe PageRequestManager sont déclenchés et tous les gestionnaires d'événements attachés sont appelés.

Remarque :

Pour les publications synchrones, seul l'événement pageLoaded est déclenché.

Vous pouvez écrire le script client pour gérer des événements déclenchés par la classe PageRequestManager. Différents objets d'argument d'événement sont passés aux gestionnaires pour différents événements. Le tableau suivant résume les événements de classe PageRequestManager et les classes d'argument d'événement correspondantes. L'ordre des événements dans la table est l'ordre des événements pour une publication asynchrone unique sans erreurs.

  • initializeRequest
    Déclenché avant que la demande soit initialisée pour une publication asynchrone. Les données d'événement sont passées aux gestionnaires en tant qu'objet InitializeRequestEventArgs. L'objet rend disponibles l'élément qui a provoqué la publication et l'objet de la demande sous-jacente.

  • beginRequest
    Déclenché juste avant que la publication asynchrone soit envoyée au serveur. Les données d'événement sont passées aux gestionnaires en tant qu'objet BeginRequestEventArgs. L'objet rend disponibles l'élément qui a provoqué la publication et l'objet de la demande sous-jacente.

  • pageLoading
    Déclenché après que la réponse de la plus récente publication asynchrone a été reçue, mais avant que toute mise à jour de la page. Les données d'événement sont passées aux gestionnaires en tant qu'objet PageLoadingEventArgs. L'objet fournit des informations à propos des panneaux qui vont être supprimés et mis à jour à la suite de la dernière publication asynchrone.

  • pageLoaded
    Déclenché après que les régions de page ont été mises à jour après la publication la plus récente. Les données d'événement sont passées aux gestionnaires en tant qu'objet PageLoadedEventArgs. L'objet rend disponibles des informations à propos des panneaux créés ou mis à jour. Pour les publications synchrones, les panneaux peuvent seulement être créés, mais pour les publications asynchrones, les panneaux peuvent être à la fois créés et mis à jour.

  • endRequest
    Déclenché lorsque le traitement de la requête est fini. Les données d'événement sont passées aux gestionnaires en tant qu'objet EndRequestEventArgs. L'objet fournit des informations à propos des erreurs qui se sont produites et de leur traitement. Il rend également l'objet de réponse disponible.

Si vous utilisez la méthode RegisterDataItem du contrôle ScriptManager pour envoyer des données supplémentaires pendant une publication asynchrone, vous pouvez accéder à ces données à partir des objets PageLoadingEventArgs, PageLoadedEventArgset EndRequestEventArgs.

La séquence d'événements selon le scénario. L'ordre du tableau précédent concerne une publication asynchrone unique réussie. D'autres scénarios incluent :

  • Plusieurs publications, la plus récente ayant priorité ; il s'agit du comportement par défaut. Uniquement les événements pour la publication asynchrone la plus récente sont déclenchés.

  • Plusieurs publications, dont l'une est prioritaire, annulant toutes les publications ultérieures jusqu'à ce qu'elle s'achève. Seul l'événement initializeRequest est déclenché pour les publications annulées.

  • Une publication asynchrone arrêtée. Si la publication est arrêtée, certains événements ne peuvent pas être déclenchés.

  • Une requête initiale (HTTP GET) d'une page ou une actualisation de page. Lors du chargement initial d'une premier ou lorsqu'elle est actualisée dans le navigateur, seul l'événement pageLoaded est déclenché.

Arrêt et annulation de publications asynchrones

Deux tâches courantes arrêtent une publication asynchrone en cours d'exécution et annulent une nouvelle requête avant qu'elle ne commence. Pour exécuter ces tâches, vous devez procédez comme suit :

  • Pour arrêter une publication asynchrone existante, vous appelez la méthode abortPostback de la classe PageRequestManager.

  • Pour annuler une nouvelle publication asynchrone, vous gérez l'événement initializeRequest de la classe PageRequestManager et définissez la propriété cancel à true.

Arrêt d'une publication asynchrone

L'exemple suivant indique comment arrêter une publication asynchrone. Le script du gestionnaire d'événements initializeRequest vérifie si l'utilisateur a choisi d'arrêter la publication. Dans l'affirmative, le code appelle la méthode 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>

Pour plus d'informations, consultez Annulation d'une publication (postback) asynchrone.

Annulation d'une nouvelle publication (postback) asynchrone

L'exemple suivant indique comment donner la priorité à une publication asynchrone spécifique. Elle annule toutes les publications asynchrones ultérieures jusqu'à l'aboutissement de la publication en cours. (Par défaut, la publication asynchrone la plus récente a priorité.) Le gestionnaire d'événements initializeRequest vérifie si la publication asynchrone a été initialisée dans la page par un élément prioritaire. Si c'est le cas, toutes les publications suivantes sont annulées en définissant la propriété cancel de l'objet InitializeRequestEventArgs. L'événement InitializeRequestEventArgs hérite de la classe CancelEventArgs, où la propriété cancel est définie.

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

Pour plus d'informations, consultez Accord de priorité à une publication (postback) asynchrone spécifique.

Pour définir un message d'erreur personnalisé

L'exemple suivant indique comment afficher un message d'erreur personnalisé lorsqu'une erreur se produit pendant une publication asynchrone. L'événement AsyncPostBackError du contrôle ScriptManager est géré par le code serveur et les informations concernant l'erreur sont envoyées au navigateur pour y être affichées.

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

Pour plus d'informations, consultez Personnalisation de la gestion des erreurs pour les contrôles UpdatePanel ASP.NET.

Animation des panneaux

L'exemple suivant indique comment animer un contrôle UpdatePanel pour notifier à l'utilisateur que le contenu a été modifié. Lorsque vous cliquez sur les contrôles LinkButton, une bordure autour du contrôle UpdatePanel s'affiche brièvement.

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

Pour plus d'informations, consultez Procédure pas à pas : animation des contrôles UpdatePanel ASP.NET.

Voir aussi

Concepts

Vue d'ensemble de la classe PageRequestManager ASP.NET