Implementing Javascript with ASP.NET; Should I use RegisterClientScriptBlock?

If you are like me, and develop primarily server-side code, client-side JavaScript can be just a headache.  If you need to create the JavaScript to include parameters or values you derive at run-time it can be even more confusing.  ASP.NET provides the RegisterClientScriptBlock and RegisterStartupScript to help, but they may not always work best.

While I will never claim to be a Javascript expert, I simply copy and paste almost 100% of what I use from working solutions and pray, I do know a thing or two about ASP.NET and how to merge the two.  If you read the .NET SDK documentation you will find the ClientScriptManager Class, you can access this class in your server-side code like this:

' Get a ClientScriptManager reference from the Page class.
    Dim cs As ClientScriptManager = Page.ClientScript

If you follow along with the SDK documentation you will see how to register a script block and a startup client script with the RegisterClientScriptBlock and RegisterStartupScript.  The RegisterStartUpScript will put your JavaScript in the OnLoad client-side event, meaning it will be executed when the page is loaded.

The RegisterClientScriptBlock will put your JavaScript somewhere between the <Body> and </Body> tags.  This is honestly not a desirable location for your JavaScript, it should really be between the Head Tags.  I was working on a Google Map API Mashup this morning and kept getting an error dialog from Internet Explorer because the JavaScript was not in the document Head.

My solution is to add a Literal control to the Head section of my page and set the Text to the JavaScript Block.  I build the JavaScript with a StringBuilder, then set the StringBuilder text to the Literal's text.  To keep the script clean you can add vblf characters to your script.  It helps to keep it readable.  You may not care about this once it is live and working since it adds extra data to your download.

Client-Side Design Code for the literal

<head runat='server'>

      <asp:literal id='_clientScript' runat='server'></asp:literal>

</head>

<body onload='onLoad()'>

Server-Side Run-Time code:

Dim cstext2 As New StringBuilder()

cstext2.Append('<script type=text/javascript>' & vbLf)

cstext2.Append(' //<![CDATA[' & vbLf)

cstext2.Append(' function onLoad() {' & vbLf)

cstext2.Append(' [Some Functional Code Goes Here.] ' & vbLf)

cstext2.Append(' //]]>' & vbLf)

cstext2.Append('</script>' & vbLf)

_clientScript.Text = cstext2.ToString()

It is kind of a shame the .NET framework team made this oversite again, in the third release of the .NET framework.  Maybe they will see fit to correct this design flaw in the next release.

Share This Article With Your Friends!