Attributes.Add: Adding Javascript Click Events Programmatically in Code-Behind
I'm going to demonstrate how to add javascript events programmatically in codebehind using the Attributes.Add method. You may want to add your javascript attributes programmatically so that you can populate the values from a database.
For demonstration purposes, I'm going to add javascript click events to an image. Let's start out with this cute little script contributed by Paul Kurenkunnas that I found on Javascript.Internet.Com (click to see it in action), which enlarges and reduces an image size on click and double-click. This javascript is simple enough that anyone can use it to see Attributes.Add in action.
<img src="waterfall.jpg" width="150" height="200" onclick="this.src='waterfall.jpg';this.height=400;this.width=300" ondblclick="this.src='waterfall.jpg';this.height=200;this.width=150">
Next in our code in front, we place an image control:
<asp:Image ID="Image1" runat="server" />
In the codebehind, we want to programmatically setup everything else. Notice I hard-code in the dimensions and URL, but you could easily retrieve the values from a database table and use them instead. This demo is primarily for the purpose of showing how to use the Attributes.Add and ResolveClientUrl methods:
VB.net:
Image1.ImageUrl = "~/site/images/MyImage.jpg"
Dim imageSrc As String = ResolveClientUrl(Image1.ImageUrl)
Image1.Attributes.Add("onclick", "this.src='" & _
imageSrc & "';this.height=600;this.width=400")
Image1.Attributes.Add("ondblclick", "this.src='" & _
imageSrc & "';this.height=300;this.width=200")
C#:
Image1.ImageUrl = "~/site/images/MyImage.jpg";
string imageSrc = ResolveClientUrl(Image1.ImageUrl);
Image1.Attributes.Add("onclick", "this.src='" + imageSrc +
"';this.height=600;this.width=400");
Image1.Attributes.Add("ondblclick", "this.src='" + imageSrc +
"';this.height=300;this.width=200");
The code generated within the browser is:
<img id="ctl00_MainBody_Image1"
onclick="this.src='../../../site/images/MyImage.jpg';
this.height=600;this.width=400"
ondblclick="this.src='../../../site/images/MyImage.jpg';
this.height=300;this.width=200"
src="../../../site/images/MyImage.jpg" style="border-width:0px;" /><br />
Notice the image path was originally setup with:
"~/site/images/MyImage.jpg"
We must use the ResolveClientUrl method to obtain a URL that can be used by the browser:
../../../site/images/MyImage.jpg
Just FYI, don't put a height and width for the image or the resizing won't work.
The Attributes.Add method can be added to numerous controls, such as images, buttons, comboboxes, labels, textboxes, radio buttons, checkboxes and more.
[SIGNATURE]