views:

153

answers:

2

I created an asp.net Server control that derives from a LinkButton, and renders a small javascript function to the page.

I want to use this control many times on the page, but just want the javascript to be rendered once on the page. On the other hand, I rather not manually add it in a js file, because i don't want to have a chance of forgetting to add the js file in the future.

What will be the best way to go about doing this ?

+5  A: 

Preventing duplication in client scripts

Use a registration method such as Page.ClientScript.RegisterClientScriptBlock(..). There are a couple of overloads but they all work in a similar fashion. It's smart enough to render the script only once no matter from how many control instances it's issued.

Microsoft remarks in the MSDN documentation:

A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page. Attempting to register a script that is already registered does not create a duplicate of the script.

The MSDN docs also contain sample code such as this:

// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
  StringBuilder cstext2 = new StringBuilder();
  cstext2.Append("<script type=text/javascript> function DoClick() {");
  cstext2.Append("Form1.Message.value='Text from client script.'} </");
  cstext2.Append("script>");
  cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}

Other similar registration methods

Different methods can be used to register your client script in different ways - see each of the ClientScriptManager.RegisterClientScript*(..) methods in MSDN for more detail about each. They're all built to prevent duplication in the rendered page.

This gives you the freedom to output scripts at the control level without worrying or having to track or count scripts.

Edit:

The ClientScriptManager instance is accessed through the Page.ClientScript property.

John K
Thanks, Exactly what i needed! :)
gillyb
A: 

You can use the Page.RegisterClientScriptBlock method.

Here is an example from the MSDN:

if (!this.IsClientScriptBlockRegistered("clientScript"))
{
  // Form the script that is to be registered at client side.
  String scriptString = "<script language=\"JavaScript\"> function DoClick() {";
  scriptString += "myForm.show.value='Welcome to Microsoft .NET'}<";
  scriptString += "/";
  scriptString += "script>";
  this.RegisterClientScriptBlock("clientScript", scriptString);
}

HTH

Pavel Nikolov