Embedding JavaScript in ASP.NET...

JavaScript can be dynamically added to ASP.NET pages within the code-behind page or through a custom control. Each has the ability to do this through methods defined in the Page class, RegisterClientScriptBlock and RegisterStartupScript.


By: Brian Mains Date: February 6, 2005 Download the code.

ASP.NET pages implement JavaScript in an application either for validation purposes or visual ones. The language is still very functional, and has a lot of capabilities, especially with the advent of DHTML. JavaScript can still be added to an ASP.NET page within the HTML code, or can be added in the server-side code. To render it server-side, don’t use the Response.Write method. Instead, the Page class has two overloaded methods to perform these capabilities:

Page.RegisterStartupScript - This method adds JavaScript to the web form right before the ending </form> tag.
Page.RegisterClientScriptBlock - This method adds JavaScript to the web form, right after the <form runat="server"> declaration.

Multiple scripts can be added to the page; each of these scripts uses a key that designates that specific block of script. Through IsClientScriptBlockRegistered and IsStartupScriptRegistered, these methods check to see if a script has been defined for a specific key. This is useful if scripts are being added to a page dynamically. It is important to note that these functions do not render the <script> element to the HTML; thus, any scripting language can be used. The caveat to this is the importance of ensuring that all script rendered has a script tag.

Also useful is the ability to render function calls to existing script within the page. Define a script in the HTML that includes one or several functions within it. By calling Page.RegisterClientScriptBlock("myMethod", "<script>method()</script>"), the page will trigger one of the predefined JavaScript methods.

Each ASP.NET server control in the web environment has a ClientID property, which should be used when making references client-side. The ClientID does not consist of the simple ID parameter for ASP .NET controls; in most cases. This is definitely the case for list controls such as the RadioButtonList or CheckBoxList controls.

JavaScript can be emitted for custom controls also. Custom controls emit JavaScript in the same way that an ASP.NET web form does. Custom controls, inheriting from System.Web.UI.Control (which includes the HtmlControl and WebControl classes also) have a Page property that contains the reference to the System.Web.UI.Page that the control resides in. Through this Page property, the aforementioned methods above can be used within server controls as well.

Server controls often use scripting to add additional bells and whistles to an application. For example through JavaScript, the developer can add mouseover or mouseout events to HTML elements, change CSS classes for an element, and a myriad of other things. The only restrictions in control development are really thinking outside-the-box to develop outstanding and fully-functional controls. For example, JavaScript provides the capabilities to perform dragging and dropping support for a custom DataGrid control. To see an example of this, Dino Esposito has an excellent article illustrating the reorganization of column headers. This article can be found at: http://msdn.microsoft.com/msdnmag/issues/04/01/CuttingEdge/default.aspx.

VBscript can also be generated with user controls. Unfortunately, VBscript is only supported by Internet Explorer, being that VBscript is a Microsoft initiative. It is possible to render VBscript for Internet Explorer browsers and JavaScript for other browsers, if so desired.

The attached project renders several alert statements, to illustrate how and when the JavaScript is rendered. The project runs through and displays the alerts, stating when the script ran. The HTML rendered for the custom control and the page alerts are shown below:

<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
lt;/HEAD>
lt;body>
<form name="Form1" method="post" action="ex01.aspx" id="Form1">
<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" value="dDwxNDk0MjczNzkzOzs+s/eyuOjXsRUMbhzwqT242jnG3O4=" />

<script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
  var theform;
  if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
    theform = document.Form1;
  }
  else {
    theform = document.forms["Form1"];
  }
  theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
  theform.__EVENTARGUMENT.value = eventArgument;
  theform.submit();
}
// -->
</script>
<script>alert('Control has added script');</script>

<script>alert('script 1 run');</script>

<script>alert('script 3 run');</script>

<P>
This is a document, that writes test javascript statements. Invoke a postback
to test another response:
<a id="lnk" href="javascript:__doPostBack('lnk','')">Invoke Postback</a><BR>
<BR>
</P>
<P>
<span id="MyControl1"></span></P>
<script>alert('script 2 run');</script>

<script>alert('script 4 run');</script>

</form>
</body>
</HTML>

Note the link that can perform postback. When posted back, the HTML appears as such:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm1</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
lt;/HEAD>
lt;body>
<form name="Form1" method="post" action="ex01.aspx" id="Form1">
<input type="hidden" name="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" value="dDwxNDk0MjczNzkzOzs+s/eyuOjXsRUMbhzwqT242jnG3O4=" />

<script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
  var theform;
  if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
    theform = document.Form1;
  }
  else {
    theform = document.forms["Form1"];
  }
  theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
  theform.__EVENTARGUMENT.value = eventArgument;
  theform.submit();
}
// -->
</script>
<script>alert('Control has added script');</script>

<script>alert('script 1 run');</script>

<P>
This is a document, that writes test javascript statements. Invoke a postback
to test another response:
<a id="lnk" href="javascript:__doPostBack('lnk','')">Invoke Postback</a><BR>
<BR>
</P>
<P>
<span id="MyControl1"></span></P>
<script>alert('script 2 run');</script>

</form>
</body>
</HTML>

This is how JavaScript can be implemented in your pages and controls in the code-behind. This is a simple example to show where the JavaScript is embedded and how it is added.

You may download the code here.