Share via


Developing a Simple ASP.NET Server Control

This topic walks you through the steps of authoring a simple custom server control that has one property and does not raise or handle events.

To author a simple ASP.NET server control

  1. Define a class that directly or indirectly derives from System.Web.UI.Control.

    using System;
    using System.Web.UI;
    public class FirstControl : Control{...}
    [Visual Basic]
    Imports System
    Imports System.Web.UI
    Public Class FirstControl   Inherits Control
    End Class
    

    The using directive allows code to reference types from a namespace without having to use the fully qualified name. Thus Control resolves to System.Web.UI.Control.

  2. Enclose your control in a namespace. You can define a new namespace or use an existing namespace. The namespace name is the value of the namespace pseudo-attribute in the Register page directive. (For example, <%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %>). For an example of using a custom control on an ASP.NET page, see the example at the end of this topic.

    namespace CustomControls
    {
          public class FirstControl : Control {...}
    ...
    }
    [Visual Basic]
    Namespace CustomControls
       Public Class FirstControl
          Inherits Control
          ...
       End Class
    End Namespace
    
  3. Define properties needed by your control. The following code fragment defines a property named Message. Properties are like smart fields and have accessor methods.

    private String message = "Hello";
    //The Message property.
          public virtual String Message{
                get{
                      return message;
                }
                set{
                      message = value;
                }
          }
    [Visual Basic]
    Private _message As String = "Hello"
    Public Overridable Property Message() As String
       Get
          Return _message
       End Get
       Set
          _message = value
       End Set
    End Property
    

    For more information about properties, see Properties Overview. To define properties that maintain their state across round trips, see Maintaining State in a Control.

  4. Override the Render method that your control inherits from Control. This method provides the logic for sending HTML to a client browser. The HTML that your control sends to the client is passed as a string argument to the Write method of an instance of System.Web.UI.HtmlTextWriter, as in the following example.

    protected override void Render( HtmlTextWriter writer)
                {
                writer.Write("<font> "+ this.Message + "<br>" +
                            "The date and time on the server: " +      
                             System.DateTime.Now.ToLongTimeString()
                             + "</font>");
                }
    [Visual Basic]
    Protected Overrides Sub Render(writer As HtmlTextWriter)
       writer.Write(("<font> " & Me.Message & "<br>" & _
          "The time on the server is " & _
          System.DateTime.Now.ToLongTimeString() & _
          "</font>"))
    End Sub
    

    The class System.DateTime that is accessed in this code fragment is a utility class that provides date and time information. Note that this class is invoked on the server and hence returns the time on the server.

    In the code fragment, raw HTML is simply passed as a string argument to the Write method of HtmlTextWriter. For details about using the methods of HtmlTextWriter to simplify HTML rendering and for rendering a control that derives from WebControl, see Rendering an ASP.NET Server Control.

    For simplicity, in this example FirstControl derives from Control. If you are authoring a control that does its own rendering, derive from System.Web.UI.WebControls.WebControl so that your control can inherit UI-specific properties.

  5. Add run-time and design-time attributes to provide custom metadata for your control as needed. Run-time attributes are required by some controls. Examples of controls that need run-time attributes are those that expose templates, perform data binding, or need custom parsing logic. See Developing a Templated Control for examples of run-time attributes. Design-time attributes are needed if your control will be used in a visual designer such as Visual Studio .NET. Design-time attributes are not required by the common language runtime, but they provide metadata that is essential for displaying a control at design time. The code fragment below applies a design-time attribute to the Message property defined in step 2.

    [Description("A message string to display to the user")]
    public virtual String Message{...}
    [Visual Basic]
    <Description("A message string to display to the user")> _
    Public Overridable Property Message() As String
       ...
    End Property
    

    For more information about design-time attributes, see Design-Time Attributes for Components and Attributes and Design-Time Support.

  6. Save, compile, and deploy the control by executing the following steps.

    1. Create a subdirectory named /bin in your application's root directory.
    2. Compile the source file into an assembly (.dll) and save the assembly in your application's /bin subdirectory.

    For example, if your source code is in C# and you save it to a file named FirstControl.cs, you can execute the following command from the directory containing the source file.

    csc /t[arget]:library /out:[path to bin]bin\CustomControls.dll /r[eference]:System.Web.dll /r:System.dll FirstControl.cs
    

    The /r option informs the compiler which assemblies are referenced by your control.

    Your control is now compiled and ready to be used from any ASP.NET page in your application's root directory (or any of its subdirectories).

The complete code for FirstControl follows. The control is enclosed in the namespace CustomControls.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
      public class FirstControl : Control
      {
            private String message = "Hello";
            
            public virtual String Message
            {
                  get
                  {
                        return message;
                  }
                  set
                  {
                        message = value;
                  }
            }
            
            protected override void Render( HtmlTextWriter writer)
            {
            writer.Write("<font> "
                        + this.Message + "<br>" + "The time on the server is " + System.DateTime.Now.ToLongTimeString()
                        + "</font>");
                  
            }
      
      }
}
[Visual Basic]
Option Explicit
Option Strict

Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace CustomControls
   Public Class FirstControl
      Inherits Control
      Private _message As String = "Hello"
      
      Public Overridable Property Message() As String
         Get
            Return _message
         End Get
         Set
            _message = value
         End Set
      End Property
      
      Protected Overrides Sub Render(writer As HtmlTextWriter)
         writer.Write(("<font> " + Me.Message + "<br>" + "The time on the server is " + System.DateTime.Now.ToLongTimeString() + "</font>"))
      End Sub
   End Class
End Namespace

Using FirstControl on an ASP.NET Page

The following ASP.NET page uses the custom control created in the preceding example. The Register page directive allows a page developer to create an alias for a namespace and also provides ASP.NET with the name of the assembly that contains the control. The example creates the alias Custom for the CustomControls namespace.

<%@ Register TagPrefix="Custom" Namespace="CustomControls" Assembly = "CustomControls" %>
<html>
   <body>   
      <form  runat=server>          
          Here is a custom ASP.NET server control.<br><br>
          <Custom:FirstControl Message= "This control tells time. "  runat=server/> 
       <br>                               
      </form>
   </body>
</html>

See Also

Properties in ASP.NET Server Controls | Events in ASP.NET Server Controls