Using client-side script libraries in a .net UserControl

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:

  • RegisterClientScriptBlock: Puts the script block at the top of the page
  • IsClientScriptBlockRegistered: Boolean indicating script is already on page
  • RegisterStartupScript: Puts the script block at the bottom of the page
  • IsStartupScriptRegistered: Boolean indicating startup script is already on page
  • RegisterArrayDeclaration: Writes a single block of client-side script that defines an array
  • RegisterOnSubmitStatement: Creates a single OnSubmit function for the page
  • RegisterHiddenField: Creates a single instance of a shared hidden input field

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.

Facebooktwittermail