November 5, 2004
Let’s suppose that you’re trying to write a UserControl in ASP.net derived from any existing .net control. You want this control to output some client-side script for input validation, DHTML manipulation, etc. However, if there is more than one instance of your control, you probably don’t want more than one copy of the script on the page. It turns out, that this is quite easy to accomplish with one of a group of functions that the Page object exposes.
These functions are:
To write out a single block of code on the page for instance, just write something like the following in the Page_Load event (class is not complete):
Public Class ClockControl
Inherits System.Web.UI.UserControl
Const csScriptKey As String = “ClockControl_ScriptLibrary”
Dim scriptString As String=”
“
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If (Not Me.Page.IsClientScriptBlockRegistered(csScriptKey))Then
Me.Page.RegisterClientScriptBlock(csScriptKey,scriptString)
End If
End Sub
…
End class
This will ensure that only one < script src = tag will be written to the page regardless of how many instances of your control are hosted on the page. You can, of course, use this to control the output of any valid Script/HTML/text/XML/etc.
Follow