Introduction:
This article describes an easy approach to the
construction of a custom ASP.NET 2.0 image button control that contains both a
mouse-over effect and calls a JavaScript function when clicked. Whilst the
article is pretty simple and the code fairly trivial, the concepts illustrated
by means of this example are relatively important and are key to integrating
client side functionality into an ASP.NET 2.0 project.
The two important items to pull from this article are:
- That you can add attributes to a custom control,
and
- That you can embed and evoke JavaScript functions
from a custom control.
One possible use for this control may be to drop
several of them into a panel and use the panel and collection as a toolbar.
Naturally the control would work just fine as a standalone control as well.
Getting Started:
In order to get started, open up the Visual Studio 2005
IDE and start a new project. From the new project dialog (Figure 1), under
project types, select the "Windows" node from beneath "Visual Basic", then
select the "Web Control Library" template in the right hand pane. Key in a name
for the project and then click "OK".
Once the project has opened; right click on the
solution and click on the "Add" menu option, and then select "New Item". When
the "Add New Item" dialog appears (Figure 2), select the "Web Custom Control"
template, after selecting the template, key "MOEbutton.vb" into the name field
and then click "Add" to close the dialog. You may now delete the default web
control that was created when the project was originally initialized from the
template.
At this point, we should have an open web control
library project with a single web control named "MOEbutton.vb" in that project.
One last step prior to writing the code for this project will be to add in one
needed reference. To add this reference, double click on the "My Project" icon
in the solution explorer to open "My Project", from here, select the
"References" tab, and then click the "Add" button. When the "Add Reference"
dialog opens, select the .NET tab, and search down the list until you find the "System.Design"
reference. Select this library and click on the "OK" button.
Figure 1: Visual Studio 2005 New Project Dialog
Figure 2: Add New Item Dialog
Navigate back to the "MOEbutton.vb" file and, at the
top of the file, add in the import statement highlighted below:
Imports
System
Imports
System.ComponentModel
Imports
System.Web
Imports
System.Web.UI
Imports
System.Web.UI.WebControls
Imports
System.Web.UI.Design
<DefaultProperty("Text"),
ToolboxData("<{0}:MOEbutton
runat=server></{0}:MOEbutton>")>_
Public
Class MOEbutton
Inherits WebControl
We are now ready to add the code necessary to make this
control functional. First off, we need to create a few private member
variables; these variables will be used to contain the paths to the image files
used to display the normal and mouse-over effects on the control, to contain a
string with the JavaScript to be applied to the button's on click event, and a
declaration of an HTML input image control that will be used as the basis for
this customization (note that the HTML Input Image button is declared with
events). To accomplish these steps, create a "Declarations" region and key in
the following variable declarations:
#Region
"Declarations"
'create private member variables used by this control
Private mMouseOverImage
As String
Private mMouseOutImage
As String
Private mJavaScriptCall
As String
Private WithEvents
imgButton As HtmlControls.HtmlInputImage
#End
Region
The next thing to do is to set up a couple of simple
initialization settings; we can do that in the public sub new declaration and in
the MOEbutton load event (add a Methods region and key in the following):
#Region
"Methods"
Public Sub
New()
'initialize new controls with a default height and
width
Me.Width = 24
Me.Height = 24
End Sub
Private
Sub MOEbutton_Load(ByVal
sender As Object,
ByVal e As
System.EventArgs)
Handles Me.Load
EnsureChildControls()
End Sub
#End
Region
Once the variables are declared, we will need to
provide public properties to expose the control's properties to the control
user; in order to accomplish these steps, create a "Properties" region and key
in the following code:
#Region
"Properties"
' create public properties for member variables
<Category("Button
Images")>_
<Browsable(True)>_
<Description("Set
path to mouseover image file.")>_
<Editor(GetType(System.Web.UI.Design.UrlEditor),
GetType(System.Drawing.Design.UITypeEditor))>_
Public Property
MouseOverImage() As
String
Get
Return mMouseOverImage
End Get
Set(ByVal
value As String)
mMouseOverImage
= value
End Set
End Property
<Category("Button
Images")>_
<Browsable(True)>_
<Description("Set
path to mouseout image file.")>_
<Editor(GetType(System.Web.UI.Design.UrlEditor),
GetType(System.Drawing.Design.UITypeEditor))>_
Public Property
MouseOutImage() As
String
Get
Return mMouseOutImage
End Get
Set(ByVal
value As String)
mMouseOutImage
= value
End Set
End Property
<Category("JavaScript")>_
<Browsable(True)>_
<Description("Set
javascript string for onclick event.")>_
Public Property
JavaScriptCall() As
String
Get
Return mJavaScriptCall
End Get
Set(ByVal
value As String)
mJavaScriptCall
= value
End Set
End Property
#End
Region
Note that, in the attributes section above each file
path related property declaration, the code specifies an editor and further that
the editor specified is defined as the URL Editor. Adding this attribute to the
control specifies to the IDE how the property is to be edited; in this instance,
when the control user sets the image file path properties for the control, the
property grid will display a button with an ellipsis in it at the right hand
side of the text box. If the user clicks on the button, the IDE will open the
URL editor and will permit the user to use that editor to navigate to the image
file and set the image file path property through that editor's dialog.
Properties set in this manner will be persisted within
the control user's project. Note that the URL editor will prefix the selected
path with a tilde and a slash, neither of which is useful in this context, you
may wish to parse the string returned from the URL editor (in the Set region of
each image file path property) to strip off the first two characters before
storing the selection). This path will be passed to the "onmouseover" and "onmouseout"
calls and if the tilde is present, the file will not be located.
<Editor(GetType(System.Web.UI.Design.UrlEditor),
_ GetType(System.Drawing.Design.UITypeEditor))>_
At this point, the only thing left to do is to define
how the control will be rendered. To complete this step, create a "Rendering"
region and, within this region, override the CreateChildControls( ) sub with the
following code:
#Region
"Rendering"
Protected Overrides
Sub CreateChildControls()
imgButton =
New HtmlControls.HtmlInputImage()
imgButton.Src =
MouseOutImage.ToString()
imgButton.Attributes.Add("onmouseover",
"this.src='" & _
MouseOverImage.ToString() & "';")
imgButton.Attributes.Add("onmouseout",
"this.src='" & _
MouseOutImage.ToString()
& "';")
imgButton.Attributes.Add("onclick",
JavaScriptCall.ToString())
Controls.Add(imgButton)
End Sub
#End
Region
Within this code there are a few things worth looking
at; first, you will note that a new instance of an HTML Input Image control is
created. After this object is created, it's "src" property is set to point to
the path stored for the MouseOutImage property. Next, the "onmouseover" and "onmouseout"
attributes are added to the imgButton control and their image source files are
set to be updated whenever the "onmouseover" or "onmouseout" events are fired.
Next up, the "onclick" attribute is added to the control and the JavaScript
string contained in the JavaScriptCall property is assigned to the "onclick"
event. While this example is basic and uses only a string containing a simple
JavaScript call, the function could also name a JavaScript function contained in
an external registered JavaScript file or could contain a complex function
defined within this class and subsequently registered for later use.
The control is now complete. Prior to testing the
control, rebuild the project. Once that has been completed and any errors
encountered are repaired, it is time to test the control. To test the control,
add a new web site project to the web control library project currently open.
Once the test web site has been created, set the test project as the start up
project by right clicking on the web site solution in the solution explorer and
selecting the "Set as Start Up Project" menu option. Next, locate the
Default.aspx page in the web site solution, right click on this page and select
the "Set as Start Page" menu option.
If you downloaded the project, you can configure a
virtual directory pointing at the example website and examine it instead of
creating one from scratch. The example project contains two subordinate
projects, one containing the web class library with the single custom web
control (MOEbutton) and a sample website with additional files needed to support
the demonstration.
If you configure the sample project and start the
default page, you will see a collection of the MOEbutton controls arranged at
the top of the page in a manner similar to a toolbar. The controls each have a
mouse over effect which consists of an alternate version of the normal icon, and
some JavaScript calls, some to launch an alert, and one to open a new window.
Aside from the properties created in support of the
MOEbutton class, as the class inherits from the WebControl class, all of the
properties and methods of that class are also included at no extra charge.
Therefore it requires no additional effort to permit the control user to set the
background color or border characteristics, or to define tooltips without
writing any additional code.
Once the site is up and running, you should observe the
following displayed in your browser window.
Figure 3: MOE Button Example in Internet Explorer