Exportar (0) Imprimir
Expandir Tudo
Este artigo foi traduzido por máquina. Coloque o ponteiro do mouse sobre as frases do artigo para ver o texto original. Mais informações.
Tradução
Original

Criando um controle extensor para associar um comportamento do cliente a um controle do servidor Web

Funcionalidade AJAX no ASP.NET permite que você expanda os recursos de um aplicativo da Web para criar uma rica experiência de usuário. You can use the ECMAScript (JavaScript), DHTML, and AJAX capabilities of the Web browser to include visual effects, client processing such as validation, and so on.

ObservaçãoObservação

Este é um tutorial avançado para desenvolvedores que desejam criar controles personalizados ou adicionar recursos Ajax a um controle. Para trabalhar com controles que já possuem os recursos do Ajax, consulte o ASP.NETToolkit de controleAJAX .

Este tutorial mostra como criar um controle do extensor que encapsula um cliente comportamento e links-lo para um controle de servidor Web . O comportamento do cliente adiciona funcionalidade a elementos de modelo de objeto de documento (DOM) do navegador. The extender control is then associated with one or more types of ASP.NET server controls to add the behavior to those server controls. You can associate more than one extender control with an ASP.NET server control.

In this tutorial you will learn how to do the following:

  • Criar um controle extensor que encapsula o comportamento do cliente e que está ligado aos controles de servidor Web em uma página da Web ASP.NET.

  • Criar um comportamento do cliente que está associado com o controle do extensor de servidor Web .

  • Lidar com eventos do DOM do navegador usando o comportamento do cliente.

    ObservaçãoObservação

    You can also add rich client capabilities to ASP.NET server controls without a separate extender control. For an example of how to create a Web server control that includes the same client capability that is shown in this tutorial, see Adicionando recursos de cliente a um controle de servidor Web.

  • Compilar o controle extensor personalizado em um assembly e incorporar arquivos JavaScript associados como recursos no mesmo conjunto.

  • Referenciar o controle extensor personalizado compilado em uma página ASP.NET com AJAX habilitado.

Um projeto de Visual Studio com código-fonte está disponível para acompanhar este tópico: Download.

Este tutorial implementa um comportamento cliente simples que realça um controle em um página da Web (como um TextBox ou um controle Button) quando o controle é selecionado (ou tiver foco) no navegador. Por exemplo, o controle pode alterar a cor do plano de fundo quando ele está com o foco, e, em seguida, retornar à cor padrão quando o foco mudar para outro controle.

Para implementar esse comportamento , o controle do cliente neste tutorial requer os recursos que estão listados na tabela a seguir .

Necessário Recurso

Implementation

Uma forma de realçar um elemento DOM.

Para realçar um elemento DOM em uma página da Web ASP.NET, o controle de cliente aplica uma folha de estilo em cascata (CSS), que é identificado por um nome da classe. This style is user configurable.

A way to return the DOM element to its non-highlighted state.

To remove the highlight from a DOM element in an ASP.NET page, the client control applies a CSS style, which is identified by a class name. Este estilo é configurável pelo usuário e é aplicado ao elemento DOM como o estilo padrão.

A way to identify when a DOM element is selected.

Para identificar quando um elemento DOM é selecionado (recebe o foco), o controle dispara o evento onfocus do elemento DOM.

A way to identify when a DOM element is not selected.

Para identificar quando um controle não estiver mais selecionado, o controle dispara o evento onblur do elemento DOM.

To encapsulate the client behavior for use by ASP.NET page developers, you can use an extender control. An extender control is a Web server control that inherits the ExtenderControl abstract class in the System.Web.UI namespace. Extender controls can be applied to specific Web server control types. You identify the types of Web server controls to which an extender control can be applied by using the TargetControlTypeAttribute attribute.

The extender control in this tutorial can be applied to any kind of Web server control. O exemplo a seguir mostra a definição de classe.


[TargetControlType(typeof(Control))]
public class FocusExtender : ExtenderControl


The new extender control includes two properties that are used to implement the client requirements:

  • HighlightCssClass, which identifies the CSS class that will be applied to the DOM element to highlight the control when it has focus.

  • NoHighlightCssClass, which identifies the CSS class that will be applied to the DOM element when it does not have focus.

Inheriting the ExtenderControl Abstract Class

The following table lists members of the ExtenderControl abstract class that you must implement in an extender control.

MEMBER

Descrição

GetScriptDescriptors

Retorna uma coleção de ScriptDescriptor objetos que representam componentes de cliente do ECMAScript (JavaScript). This includes the client type to create, the properties to assign, and the events to add handlers for.

GetScriptReferences

Returns a collection of ScriptReference objects that contain information about the client-script libraries to be included with the control. The client-script libraries define the client types and include any other JavaScript code that is required for the control.

The extender control in this tutorial uses the GetScriptDescriptors() method to define the instance of the client behavior type. The control creates a new ScriptBehaviorDescriptor object (the ScriptBehaviorDescriptor class derives from the ScriptDescriptor class) and includes the object in the return value for the GetScriptDescriptors method.

The ScriptBehaviorDescriptor object includes the name of the client class (Samples.FocusBehavior) and the ClientID value for the associated (target) Web server control. The client class name and the ClientID property values are supplied to the constructor for the ScriptBehaviorDescriptor object. A reference to the target Web server control is supplied as a parameter to the GetScriptDescriptors(Control) method. The reference can be used to determine the ClientID value of the target Web server control, which is the id value for the rendered DOM element.

The ScriptBehaviorDescriptor class is used to set the client behavior's property values, which are obtained from properties of the extender control on the server. To define the client behavior's properties, the extender control uses the AddProperty method of the ScriptBehaviorDescriptor class. The extender control then specifies the name and value for the property of the client behavior, based on the corresponding property of the server extender control. This example uses a ScriptBehaviorDescriptor object to set the values for the highlightCssClass and nohighlightCssClass properties in the client behavior.

The extender control supplies the ScriptBehaviorDescriptor object in the return value for the GetScriptDescriptors method. Therefore, whenever the Web server control is rendered to the browser, ASP.NET renders JavaScript that creates an instance of the client behavior with all defined properties and event handlers. The behavior instance is attached to the DOM element, based on the ClientID property that is rendered from the target Web server control. The following example shows declarative ASP.NET markup that includes an ASP.NET server control and the extender control from this tutorial in a page.

<asp:TextBox ID="TextBox1" runat="server" />
<sample: FocusExtender runat="server"
    ID="FocusExtender1" 
    HighlightCssClass="MyHighLight"
    NoHighlightCssClass="MyLowLight"
    TargetControlID="TextBox1" />

The rendered output of the page includes a call to the $create method that identifies the client behavior to create. It also provides values for the client behavior's properties and the id value of the DOM element that the client behavior targets. The following example shows a rendered $create method.

$create(Samples.FocusBehavior, {"highlightCssClass":"MyHighLight","nohighlightCssClass":"MyLowLight"}, null, null, $get('TextBox1'));

The extender control in this tutorial uses the GetScriptReferences method to pass the location of the script library that defines the client behavior type. In the example, this is a URL to the script file named FocusBehavior.js, which is created later in this tutorial. The reference is made by creating a new ScriptReference object, and then setting the Path property to the URL of the file that contains the client code.

The following example shows the implementations of the GetScriptDescriptors and GetScriptReferences methods.


protected override IEnumerable<ScriptReference> GetScriptReferences()
{
    ScriptReference reference = new ScriptReference();
    reference.Path = ResolveClientUrl("FocusBehavior.js");

    return new ScriptReference[] { reference };
}

protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors(Control targetControl)
{
    ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor("Samples.FocusBehavior", targetControl.ClientID);
    descriptor.AddProperty("highlightCssClass", this.HighlightCssClass);
    descriptor.AddProperty("nohighlightCssClass", this.NoHighlightCssClass);

    return new ScriptDescriptor[] { descriptor };
}


In the extender control, the GetScriptReferences method specifies a JavaScript file (FocusBehavior.js) that contains the client code for the behavior type. This section describes the JavaScript code in that file.

The client behavior code matches the members that were specified in the ScriptDescriptor objects that are returned by the GetScriptDescriptors method. A client behavior can also have members that do not correspond to members in the server extender control.

The extender control in this tutorial sets the name of the client behavior to Samples.FocusBehavior, and it defines two properties of the client behavior, highlightCssClass and nohighlightCssClass.

For more information about how to create client components and behaviors, see Criando uma Classe de Componente de Cliente Usando o Modelo Protótipo.

Criando o Namespace do cliente

O código do cliente precisa primeiro chamar o registerNamespace ométodo do Tipo classe para criar seu namespace (Samples). The following example shows how to register the client namespace.


// Register the namespace for the control.
Type.registerNamespace('Samples');


Defining the Client Class

O Samples.FocusBehavior classe define o Samples.FocusBehavior de cliente de classe. Ele inclui duas propriedades para armazenar os valores de propriedade fornecidos pelo controle de servidor Web .

Defining the Class Prototype

After the Samples.FocusBehavior class is defined, the client code defines the prototype for the class. The prototype includes property get and set accessors, and event handlers for the onfocus and onblur events of the DOM element. It also includes an initialize method that is called when an instance of the behavior is created, and a dispose method that performs cleanup when the behavior is no longer required by the page.

Defining the Event Handlers for the DOM Element

Event handlers for a client class are defined as methods of the class prototype. The handlers are associated with event delegates and with events of the browser DOM by using the addHandlers method, which is discussed later in this topic with the initialize method.

Defining the Property Get and Set Methods

Each property identified in the ScriptDescriptor object of the extender control's GetScriptDescriptors method must have corresponding client accessors. The client property accessors are defined as get_<property name> and set_<property name> methods of the client class prototype.

Implementing the Initialize and Dispose Methods

The initialize method is called when an instance of the behavior is created. Use this method to set default property values, to create function delegates, and to add delegates as event handlers.

The initialize method of the Samples.FocusBehavior class does the following:

  • Calls the initialize method of the Sys.UI.Behavior base class.

  • Calls the addHandlers method to add event delegates as handlers for the onfocus and onblur events of the associated DOM element. Note that the "on" part of the event name (for example, onfocus) is not specified.

The dispose method is called when an instance of the behavior is no longer used on the page and is removed. Use this method to free any resources that are no longer required for the behavior, such as DOM event handlers.

The dispose method of the Sample.FocusBehavior class does the following:

  • Calls the clearHandlers method to clear the event delegates as handlers for the onfocus and onblur events of the associated DOM element.

  • Calls the dispose method of the Behavior base class.

    ObservaçãoObservação

    The dispose method of a client class might be called more than one time. Make sure that the code you include in the dispose method takes this into account.

Registering the Behavior

The final task in creating the client behavior is to register the client class by calling the registerClass method. Because the class is a client behavior, the call to the registerClass method includes the JavaScript class name to register. It also specifies Behavior as the base class.

O exemplo completo abaixo inclui uma chamada para o notifyScriptLoaded ométodo do sys. Applicationclasse.

O exemplo a seguir mostra o código de JavaScript completo para o Samples.FocusBehavior comportamento do cliente. O código neste tutorial requer o arquivo JavaScript será nomeado focusbehavior. js e ser colocado no diretório de Scripts.


// Register the namespace for the control.
Type.registerNamespace('Samples');

//
// Define the behavior properties.
//
Samples.FocusBehavior = function(element) { 
    Samples.FocusBehavior.initializeBase(this, [element]);

    this._highlightCssClass = null;
    this._nohighlightCssClass = null;
}

//
// Create the prototype for the behavior.
//

Samples.FocusBehavior.prototype = {


    initialize : function() {
        Samples.FocusBehavior.callBaseMethod(this, 'initialize');

        $addHandlers(this.get_element(), 
                     { 'focus' : this._onFocus,
                       'blur' : this._onBlur },
                     this);

        this.get_element().className = this._nohighlightCssClass;
    },

    dispose : function() {
        $clearHandlers(this.get_element());

        Samples.FocusBehavior.callBaseMethod(this, 'dispose');
    },

    //
    // Event delegates
    //

    _onFocus : function(e) {
        if (this.get_element() && !this.get_element().disabled) {
            this.get_element().className = this._highlightCssClass;          
        }
    },

    _onBlur : function(e) {
        if (this.get_element() && !this.get_element().disabled) {
            this.get_element().className = this._nohighlightCssClass;          
        }
    },


    //
    // Behavior properties
    //

    get_highlightCssClass : function() {
        return this._highlightCssClass;
    },

    set_highlightCssClass : function(value) {
        if (this._highlightCssClass !== value) {
            this._highlightCssClass = value;
            this.raisePropertyChanged('highlightCssClass');
        }
    },

    get_nohighlightCssClass : function() {
        return this._nohighlightCssClass;
    },

    set_nohighlightCssClass : function(value) {
        if (this._nohighlightCssClass !== value) {
            this._nohighlightCssClass = value;
            this.raisePropertyChanged('nohighlightCssClass');
        }
    }
}

// Optional descriptor for JSON serialization.
Samples.FocusBehavior.descriptor = {
    properties: [   {name: 'highlightCssClass', type: String},
                    {name: 'nohighlightCssClass', type: String} ]
}

// Register the class as a type that inherits from Sys.UI.Control.
Samples.FocusBehavior.registerClass('Samples.FocusBehavior', Sys.UI.Behavior);

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();


O exemplo a seguir mostra o código completo para o ASP.NET página.


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>ASP.NET AJAX Behavior Sample</title>
    <style type="text/css">
    .LowLight
    {
        background-color:#EEEEEE;
    }

    .HighLight
    {
        background-color:#FFFFF0;
    }
    .LowLightButton
    {
        font-weight:normal;
        width:100px;
    }

    .HighLightButton
    {
        font-weight:bold;
        width:100px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" />
        <div>
            <table border="0" cellpadding="2">
              <tr>
                <td><asp:Label runat="server" ID="Label1" AssociatedControlID="TextBox1">Name</asp:Label></td>
                <td><asp:TextBox ID="TextBox1" runat="server" /></td>
              </tr>
              <tr>
                <td><asp:Label runat="server" ID="Label2" AssociatedControlID="TextBox2">Phone</asp:Label></td>
                <td><asp:TextBox ID="TextBox2" runat="server" /></td>
              </tr>
              <tr>
                <td><asp:Label runat="server" ID="Label3" AssociatedControlID="TextBox3">E-mail</asp:Label></td>
                <td><asp:TextBox ID="TextBox3" runat="server" /></td>
              </tr>
            </table>

            <asp:Button runat="server" ID="Button1" Text="Submit Form" />

            <sample:FocusExtender ID="FocusExtender1" runat="server"
                                  NoHighlightCssClass="LowLight"
                                  HighlightCssClass="HighLight"
                                  TargetControlID="TextBox1" />
            <sample:FocusExtender ID="FocusExtender2" runat="server"
                                  NoHighlightCssClass="LowLight"
                                  HighlightCssClass="HighLight"
                                  TargetControlID="TextBox2" />
            <sample:FocusExtender ID="FocusExtender3" runat="server"
                                  NoHighlightCssClass="LowLight"
                                  HighlightCssClass="HighLight"
                                  TargetControlID="TextBox3" />
            <sample:FocusExtender ID="FocusExtender4" runat="server"
                                  NoHighlightCssClass="LowLightButton"
                                  HighlightCssClass="HighLightButton"
                                  TargetControlID="Button1" />
        </div>

    </form>
</body>
</html>


O exemplo a seguir mostra o código completo para a classede FocusExtender. Normalmente, esse código é colocado no diretório App_Code.


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;

namespace Samples.CS
{
    [TargetControlType(typeof(Control))]
    public class FocusExtender : ExtenderControl
    {
        private string _highlightCssClass;
        private string _noHighlightCssClass;

        public string HighlightCssClass
        {
            get { return _highlightCssClass; }
            set { _highlightCssClass = value; }
        }

        public string NoHighlightCssClass
        {
            get { return _noHighlightCssClass; }
            set { _noHighlightCssClass = value; }
        }

        protected override IEnumerable<ScriptReference> GetScriptReferences()
        {
            ScriptReference reference = new ScriptReference();
            reference.Path = ResolveClientUrl("FocusBehavior.js");

            return new ScriptReference[] { reference };
        }

        protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors(Control targetControl)
        {
            ScriptBehaviorDescriptor descriptor = new ScriptBehaviorDescriptor("Samples.FocusBehavior", targetControl.ClientID);
            descriptor.AddProperty("highlightCssClass", this.HighlightCssClass);
            descriptor.AddProperty("nohighlightCssClass", this.NoHighlightCssClass);

            return new ScriptDescriptor[] { descriptor };
        }
    }
}


Any Web server control, such as the extender control in this tutorial, must be compiled before you can reference it in a Web page. You can use the dynamic compilation feature of ASP.NET version 2.0 to test Web server controls without manually compiling the controls into an assembly. This saves time when you are initially writing and debugging the Web server control code. The following steps show you how to use the App_Code folder to dynamically compile your extender control.

To put the extender control in the App_Code folder for dynamic compilation

  1. Create an App_Code folder under the root folder of the Web site.

  2. Move the .cs or .vb control source files and any related classes into the App_Code folder.

    -ou-

    If you previously added an assembly for the control to the Bin folder, delete the assembly. You continue to edit the source files in the App_Code folder. The control source code will be compiled every time that you run your project.

    ObservaçãoObservação

    You can either compile a control into an assembly and place the assembly in the Bin folder, or you can place the control's source file in the App_Code folder, but you cannot do both. If you add the control to both folders, the page parser will not be able to resolve a reference to the control in a page and will raise an error.

  3. Run the Web page. The extender control is dynamically compiled.

The following procedure describes how to test the extender control in an ASP.NET AJAX-enabled Web page. The code for the Web server control is compiled dynamically from the App_Code folder.

To use the behavior in an ASP.NET page

  1. Create a new ASP.NET Web page.

  2. If the page does not already have a ScriptManager control, add one.

  3. Create CSS style rules for text boxes that are highlighted and for the text boxes that are not highlighted.

    You can highlight the control any way that you like. For example, you can change the control's background color, add a border, or change the font of text.

  4. Adicionar um @ Register diretiva para a página e, em seguida, especifique o namespace e o TagPrefixdeatributo para o controle do extensor,

    ObservaçãoObservação

    In this example, the server control code is in the App_Code folder so that it can be dynamically compiled. Therefore, an assembly attribute is not specified.

  5. Add a TextBox and a Button control to the page and set their Id properties.

    A marcação para os controles deve incluir runat="server".

  6. Adicione uma instância do controle FocusExtender para a página .

  7. Set the TargetControlID property of the FocusExtender control to the ID of the Button control that you added previously.

  8. Set the HighlightCssClass property to the highlight CSS style, and set the NoHighlightCssClass property to the no highlight CSS style.

  9. Execute a página e selecione cada controle .

    Notice that when you select the Button control, it is highlighted.

  10. Change the TargetControlID property of the FocusExtender control to the ID of the TextBox control, and then run the page again.

    This time, the TextBox control is highlighted when it has focus. The behavior encapsulated in the FocusExtender control can be applied to different ASP.NET server controls on the page. If you want the behavior to apply to multiple controls, you can add multiple instances of the extender control to the page and associate each instance with a different ASP.NET server control.

Embedding the JavaScript component and Web server control's extension code into an assembly will make your custom extender control easier to deploy. Creating an assembly also makes it easier to manage version control for the control. In addition, controls cannot be added to the toolbox of a designer unless they are compiled into an assembly.

Para compilar o servidor personalizado controle do extensor em um assembly

  1. In the Properties window for the FocusBehavior.js file, set Build Action to Embedded Resource.

    Definir arquivo de script para recurso inserido
  2. Adicionar a seguinte propriedade ao arquivo AssemblyInfo.

    
    [assembly: System.Web.UI.WebResource("Samples.FocusBehavior.js", "text/javascript")]
    
    
    
    ObservaçãoObservação

    O arquivo AssemblyInfo.vb está no nó My Project do Solution Explorer. Se você não vir nenhum arquivo de My Project nó, faça o seguinte: sobre o projeto menu, clique em Mostrar Tudo arquivos de. O arquivo AssemblyInfo. cs está a Propriedades o nó de s.

    The WebResource definition for JavaScript files must follow a naming convention of [assembly namespace].[JavaScript File name].js.

    ObservaçãoObservação

    By default, Visual Studio sets the assembly namespace to the assembly name. You can edit the assembly namespace in the assembly's properties.

  3. No arquivo de classe FocusExtender, altere o ScriptReferenceoobjeto na GetScriptReferences script incorporado no assemblyde amostras de controle demétodo para referenciar o cliente. Para fazer isso, faça as seguintes alterações:

    • Substituir a propriedade Path com uma propriedade Assembly definida como Samples.

    • Adicionar uma propriedade Name e definir o valor para "Samples.FocusBehavior.js".

    O exemplo seguinte mostra o resultado desta alteração.

    
    		protected override IEnumerable<ScriptReference> GetScriptReferences()
    		{
    			ScriptReference reference = new ScriptReference();
    			reference.Assembly = "Samples";
    			reference.Name = "Samples.FocusBehavior.js";
    
    			return new ScriptReference[] { reference };
    		}
    
    
    
  4. Compile o projeto.

    Quando termina de compilação, você terá um assembly chamado Samples. dll. O arquivo de código JavaScript (focusbehavior) é incorporado neste assembly como um recurso.

    ObservaçãoObservação

    Remember to rebuild the class library project any time that you add new source files or change existing ones.

Você vai agora fazer referência ao controle extensor personalizado compilado em uma página da Web ASP.NET AJAX -enabled.

To reference the custom extender control in an ASP.NET AJAX-enabled Web page

  1. Criar um novo projeto ASP.NET AJAX.

  2. No diretório raiz do site , crie uma pasta Bin.

  3. Copie o assembly Samples.dll da pasta de exemplo do projeto classe Bin \Debug ou Bin\ Release para a nova pasta Bin.

  4. Adicionar uma nova página Web do ASP.NET chamada TestFocusExtender.aspx , e em seguida adicione a seguinte marcação para a nova página .

    
    <%@ Register Assembly="Samples" Namespace="Samples.CS" TagPrefix="sample" %>
    
    
    

    Porque o controle de servidor é compilado em um assembly, o @ Register diretiva tem um Assembly atributo , que referencia o assembly de amostras além da Namespace e TagPrefix atributos.

  5. Execute a página e selecione cada controle .

    When you select the FocusBehavior control, it is highlighted.

A página Web que usa o controle do extensor de personalizado compilado inclui o Assembly atributo o @ Register diretiva. Otherwise, it is the same as the Web page you used for the control in the App_Code folder.

Contribuições da comunidade

ADICIONAR
A Microsoft está realizando uma pesquisa online para saber sua opinião sobre o site do MSDN. Se você optar por participar, a pesquisa online lhe será apresentada quando você sair do site do MSDN.

Deseja participar?
Mostrar:
© 2014 Microsoft