Compartilhar via


Demonstra Passo a passo: Animar controles UpdatePanel do ASP.NET

This walkthrough describes how to animate an UpdatePanel control that was updated as a result of an asynchronous postback.

The Microsoft AJAX Library enables you to manage events in the client page life cycle.You do this by handling events of the client PageRequestManager class.In this walkthrough, you will see how to use the beginRequest and pageLoaded events to animate an UpdatePanel control when a specific control on the page causes an asynchronous postback.The beginRequest event is raised before an asynchronous postback starts and before the postback is sent to the server.The pageLoaded event is raised during postbacks and asynchronous postbacks.During this event, you can access information about what panels where created and updated as a result of the most recent postback.(For postbacks, panels are only created, but for asynchronous postbacks, panels can be both created and updated.)

Pré-requisitos

Para implementar os procedimentos no seu próprio ambiente de desenvolvimento você precisa:

  • Visual Studio 2008 ou Visual Web Developer 2008 Express Edition.

  • Um site da Web ASP.NET habilitado para AJAX.

Creating Client Script that Animates an UpdatePanel Control

In this procedure you will create an ECMAScript (JavaScript or JScript) file that defines an animation class.The class contains a method that animates an HTML DOM element.In the browser, the UpdatePanel control that you want to animate is represented as a div element.

To create client script that animates an UpdatePanel control

  1. In the AJAX-enabled ASP.NET Web site, add a JScript file and name it UpdatePanelAnimation.js.

  2. Add the following JavaScript code to the file:

    Type.registerNamespace("ScriptLibrary");
    ScriptLibrary.BorderAnimation = function(startColor, endColor, duration) {
        this._startColor = startColor;
        this._endColor = endColor;
        this._duration = duration;
    }
    ScriptLibrary.BorderAnimation.prototype = {
        animatePanel: function(panelElement) {
            var s = panelElement.style;
            var startColor = this._startColor;
            var endColor = this._endColor;
            s.borderColor = startColor;
            window.setTimeout(
                function() {{ s.borderColor = endColor; }},
                this._duration
            );
        }
    }
    ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);
    
    var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 'gray', 1000);
    var postbackElement;
    
    Sys.Application.add_load(ApplicationLoadHandler);
    function ApplicationLoadHandler() {
        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('animate') > -1) {
            for (i=0; i < updatedPanels.length; i++) {            
                panelUpdatedAnimation.animatePanel(updatedPanels[i]);
            }
        }
    
    }
    if(typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    
    Type.registerNamespace("ScriptLibrary");
    ScriptLibrary.BorderAnimation = function(startColor, endColor, duration) {
        this._startColor = startColor;
        this._endColor = endColor;
        this._duration = duration;
    }
    ScriptLibrary.BorderAnimation.prototype = {
        animatePanel: function(panelElement) {
            var s = panelElement.style;
            var startColor = this._startColor;
            var endColor = this._endColor;
            s.borderColor = startColor;
            window.setTimeout(
                function() {{ s.borderColor = endColor; }},
                this._duration
            );
        }
    }
    ScriptLibrary.BorderAnimation.registerClass('ScriptLibrary.BorderAnimation', null);
    
    var panelUpdatedAnimation = new ScriptLibrary.BorderAnimation('blue', 'gray', 1000);
    var postbackElement;
    
    Sys.Application.add_load(ApplicationLoadHandler);
    function ApplicationLoadHandler() {
        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('animate') > -1) {
            for (i=0; i < updatedPanels.length; i++) {            
                panelUpdatedAnimation.animatePanel(updatedPanels[i]);
            }
        }
    
    }
    if(typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
    

    O código executa as seguintes tarefas:

    • Registers the ScriptLibrary namespace by calling the registerNamespace method.

    • Uses the prototype design pattern to define the BorderAnimation class in the ScriptLibrary namespace.A method named animatePanel in the BorderAnimation class defines the animation logic.

    • Registers the BorderAnimation class by calling the registerClass method.

    • Creates a new instance of the BorderAnimation class.O código passa três valores para o construtor da classe: uma cor de animação, uma cor padrão e o número de milissegundos para exibir a cor de animação.

    • Defines a handler for the load event of the Sys.Application class.This class in turn defines handlers for the beginRequest and pageLoaded events of the PageRequestManager class.

    • In the beginRequest event handler, the code saves the name of the element that caused the postback.

    • If the ID of the postback element contains the word "animate", the code performs the animation in the pageLoaded event handler.

Using the Client Script with an UpdatePanel Control

In this procedure you will use the animation script in a page that contains an UpdatePanel control.The script animates the panel when the panel's contents are refreshed.

To animate an UpdatePanel control

  1. Crie uma nova página e alterne para modo de Design.

  2. If there is not already a ScriptManager control on the page, drag one from the AJAX Extensions tab of the Toolbox.

  3. In the Toolbox, double-click the UpdatePanel control to add an UpdatePanel control to the page.

  4. Click inside the UpdatePanel control and then in the Standard tab of the toolbox, double-click the Button control two times to add two buttons to the UpdatePanel control.

  5. conjunto Text propriedade para atualizar com animação e sua ID para AnimateButton1.

  6. conjunto Text propriedade para atualizar com nenhuma animação. Leave its ID as the default value of Button2.

  7. Switch to Source view and add the following style rules in a style block in the head element of the page.

    <style type="text/css">
    #UpdatePanel1 {
      width: 300px;
      height: 100px;
      border:solid 1px gray;
    }    
    </style>
    
    <style type="text/css">
    #UpdatePanel1 {
      width: 300px;
      height: 100px;
      border:solid 1px gray;
    }    
    </style>
    

    The style rules define the height, width, and border of the div element that is rendered for the UpdatePanel control.

  8. Add the following code inside the ContentTemplate element of the asp:UpdatePanel element:

    <%=DateTime.Now.ToString() %>
    
    <%=DateTime.Now.ToString() %>
    

    The code displays the time when the markup was most recently rendered.

  9. Alterne para o modo de exibição Design e selecione o controle ScriptManager.

  10. In the Properties window, select the Scripts property and click the ellipsis (…) button to display the ScriptReference Collection Editor dialog box.

  11. Clique em Adicionar para adicionar uma referência de script.

  12. Set the Path property of the script reference to UpdatePanelAnimation.js, which is the JavaScript file that you created previously.

    You add a script reference using the Scripts collection of the ScriptManager to make sure that the script is loaded after the code for the Microsoft AJAX Library has loaded.

  13. Clique em OK para fechar a caixa de diálogo Editor de Coleção ScriptReference.

  14. Save the changes and press CTRL+F5 to view the page in a browser.

  15. Click the Refresh button to refresh the panel.

    Note that the border of the panel changes color briefly.

    <%@ Page Language="VB" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" >
        <title>UpdatePanel Animation Example</title>
        <style type="text/css">
        #UpdatePanel1 {
          width: 300px;
          height: 100px;
          border:solid 1px gray;
        }    
        </style>
    </head>
    <body>
        <form id="form1" >
        <div>
            <asp:ScriptManager ID="ScriptManager1" >
            <Scripts>
            <asp:ScriptReference Path="UpdatePanelAnimation.js" />
            </Scripts>
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" >
                <ContentTemplate>
                    <%=DateTime.Now.ToString() %>
                    <asp:Button ID="AnimateButton1"  Text="Refresh with Animation" />
                    <asp:Button ID="Button2"  Text="Refresh with no Animation" />
                </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">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head id="Head1" >
        <title>UpdatePanel Animation Example</title>
        <style type="text/css">
        #UpdatePanel1 {
          width: 300px;
          height: 100px;
          border:solid 1px gray;
        }    
        </style>
    </head>
    <body>
        <form id="form1" >
        <div>
            <asp:ScriptManager ID="ScriptManager1" >
            <Scripts>
            <asp:ScriptReference Path="UpdatePanelAnimation.js" />
            </Scripts>
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" >
                <ContentTemplate>
                    <%=DateTime.Now.ToString() %>
                    <asp:Button ID="AnimateButton1"  Text="Refresh with Animation" />
                    <asp:Button ID="Button2"  Text="Refresh with no Animation" />
                </ContentTemplate>
            </asp:UpdatePanel>
    
        </div>
        </form>
    </body>
    </html>
    

Revisão

This walkthrough showed how to provide a simple animation for an UpdatePanel control when the panel's contents are refreshed.Code in a JavaScript file animates the HTML div element that is rendered by the UpdatePanel control.The JavaScript file is added to the Scripts collection of the ScriptManager control.The main logic in the script file is defined in the handlers for the beginRequest and pageLoaded events of the PageRequestManager class.

Consulte também

Conceitos

Trabalhando com eventos PageRequestManager

Referência

Classe Sys.WebForms.PageRequestManager

Classe Sys.WebForms.PageLoadedEventArgs