Let's illustrate the concept with an example:
Your ASP.NET application should display a form with several buttons on it. When clicked, some of the buttons should execute the associated (server-side) event handler code directly. Some of the buttons, however, have to display a confirmation prompt on the client browser, allowing the user to cancel the initiated execution of the command.
Because the buttons that should display the client-side confirmation are...well, buttons, it is natural (IMHO) to derive a new class from the existing System.Web.UI.WebControls.Button and add the necessary functionality there. Enter the PromptButton class:
Namespace LaMarvin.Samples.Web.DerivingBuiltinControls
Public Class PromptButton
Inherits System.Web.UI.WebControls.Button
' Our confirmation message or Nothing if no
' confirmation prompt should be displayed on the client.
Private _ConfirmMessage As String = String.Empty
Public Overridable Property ConfirmMessage() As String
Get
Return _ConfirmMessage
End Get
Set(ByVal Value As String)
_ConfirmMessage = Value
End Set
End Property
Protected Overrides Sub AddAttributesToRender( _
ByVal writer As System.Web.UI.HtmlTextWriter)
If _ConfirmMessage.Length > 0 Then
writer.AddAttribute("onclick", _
"return confirm('" + _ConfirmMessage + "');")
End If
MyBase.AddAttributesToRender(writer)
End Sub
End Class
End Namespace
First, we've declared the _ConfirmMessage member variable and the public ConfirmMessage accessor property.
Second, we've overridden the AddAttributesToRender method adding the onclick client-side script handler.
In order to use the PromptButton class in an .aspx page, the project containing the class has to be rebuilt. This is because we have to register the control's assembly by using a variant of the @Register directive that includes the Assembly attribute:
<%@ Register TagPrefix = "dc"
Namespace = "LaMarvin.Samples.Web.DerivingBuiltinControls"
Assembly = "DerivingBuiltinControls" %>
The TagPrefix "dc" is an arbitrary string that is an alias for the associated namespace (as declared by the Namespace attribute).
The Assembly attribute is the assembly DLL file name without the extension (a fully qualified assembly reference isn't necessary in this case).
Comments