NET
CHAPTER 8 ?– INTEGRATING CL IENT-SIDE SCRIPT 349
Label server control and adding an onclick attribute. The page parser is responsible for ensuring
this becomes part of the control??™s final output.
tabIndex=1 onclick="alert('TopLabel clicked!');">TopLabelThe following code shows the second option: adding the attribute to the HTML element
via the Attributes collection of the server control in the code-behind class. The recommended
place to put this type of code is in the Page_Load event because the control is fully initialized.
BottomLabel.Attributes.Add("onclick", "alert('BottomLabel clicked!');");
The two preceding techniques add the client-side script code via external manipulation of
the server control. You can add the same attribute-handling code internally to a server control
just as easily. Listing 8-1 shows a server control that inherits from the ASP.NET Label control
and adds code to an override of the OnPreRender method that generates an onclick attribute to
the final output of our new custom Label control, ClickLabel.
Listing 8-1. The ClickLabel Server Control
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.
Pages:
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462