Create and Register JavaScript on the Server
Three Easy Methods to Solve a Common Problem
October 30, 2009
UI Tips
LANGUAGES: ALL
ASP.NET VERSIONS:ALL
Create and Register JavaScript on the Server
Three Easy Methods to Solve a Common Problem
By Brad McCabe
A very common problem ASP.NET developers face is having to create JavaScript code dynamically based on server-sideevents or conditions, and then register and execute that code on a client sbrowser. A simple example of this is an event that requires server-sideprocessing, such as credit card processing or database validation. As a resultof this event, you would like to alert the user with a popup message box.
Creating a message box is simple in JavaScript you callthe alert function and pass in your text. This, however, becomes more difficultwhen you are executing server-side C# or VB code. How do you get yourserver-side code to cause a message box to pop up in users browsers?
Somehow you need to create JavaScript code with your VB orC# code and emit that code to the browser in the resulting HTML from the page.
These types of tasks are made much easier thanks to acouple of functions in the .NET Framework with which many developers areunfamiliar. The three that we will look at here are:
RegisterClientScriptBlock
RegisterStartupScript
RegisterOnSubmitStatement
All three of these functions take the same two parameters.The first parameter you will need to pass in is key. Thisis the unique identifier for the script and is used by ASP.NET to ensure thatthe same script is not registered and sent to the client multiple times.
The second parameter is the script code itself that youwish to send down to the client. One common mistake here that developers oftenmake is to leave out the required tagsaround your code. Although these methods are for registering JavaScript codefor the client, they don t automatically add these tags; they simply send thecontents of the script parameter directly to the browser.
RegisterClientScriptBlock
The first of these three functions,RegisterClientScriptBlock, will emit the client-side script that was passed injust after the opening of the Page object s
element. RegisterClientScriptBlockis an ideal function to use to register blocks of dynamically createdJavaScript functions that you plan to call later in your code:
Dim script As New System.Text.StringBuilder
With script
.Append("")
.Append("functionmyFunction() {")
.Append("alert('Hello ")
.Append(TextBox1.Text)
.Append("') }")
.Append("")
End With
RegisterClientScriptBlock("myFunction",script.ToString)
In this code example I used server-side VB code to createJavaScript code on the fly and registered the script to be emitted to theclient s browser. However, because we created a JavaScript function, this codewill not get run by the browser until we call it. For that we can use either ofthe other two functions.
RegisterStartupScript
If we wanted this code to run as soon as the page wasrunning, we could change it slightly to appear as follows:
Dim script As New System.Text.StringBuilder
With script
.Append("")
.Append("functionPage_Load() {")
.Append("alert('Hello ")
.Append(TextBox1.Text)
.Append("') }")
.Append("")
End With
RegisterStartupScript("startup", script.ToString)
In this example I tied the execution of the code to thepage load event for the document. You don t have to do this; you could emitcode that is run directly and not inside of a function. One thing to rememberis that this code is emitted right before the closing tag for the Page object s
tag. Because this code is emitted, and any JavaScriptnot inside of a function would be run as soon as the browser hits this section,you need to be careful because the page is not completely loaded and you couldhave some unintended results and errors. Hooking to the page load event is asafer approach.
RegisterOnSubmitStatement
The last of the three functions, RegisterOnSubmitStatement,is very similar. This method allows your code to access and tie to the OnSubmitevent of the page. It s a good idea that any script you emit here should be afunction call to client-side code that is registered somewhere else, eitherdirectly on the page or through a RegisterClientScriptBlock call.
You can put simple JavaScript into this method to have itexecute, but in most cases you ll be using this method to install customvalidation code or other more complex code to call before the processing of thepage submit. This is easier to maintain and easier to read if it is in aseparate JavaScript function.
Using these three very simple methods on the Page objectyou can easily create JavaScript code dynamically on the server side andregister that script in a variety of ways to execute in the client s browser.
Brad McCabe is aconsultant with Ajilon Consulting, a leading solutions provider. Brad also hasbeen a systems architect and consultant for several Fortune 500 companies andhas been a featured speaker at numerous Microsoft events around the world. Hisprimary interests include ASP.NET, Tablet PC, .NET Compact Framework, andMicrosoft s networking technologies. E-mail him at [email protected].
About the Author
You May Also Like