Skip navigation

Create and Register JavaScript on the Server

Three Easy Methods to Solve a Common Problem

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-side events or conditions, and then register and execute that code on a client s browser. A simple example of this is an event that requires server-side processing, such as credit card processing or database validation. As a result of this event, you would like to alert the user with a popup message box.

 

Creating a message box is simple in JavaScript you call the alert function and pass in your text. This, however, becomes more difficult when you are executing server-side C# or VB code. How do you get your server-side code to cause a message box to pop up in users browsers?

 

Somehow you need to create JavaScript code with your VB or C# 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 a couple of functions in the .NET Framework with which many developers are unfamiliar. 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. This is the unique identifier for the script and is used by ASP.NET to ensure that the same script is not registered and sent to the client multiple times.

 

The second parameter is the script code itself that you wish to send down to the client. One common mistake here that developers often make is to leave out the required <Script> and </Script> tags around your code. Although these methods are for registering JavaScript code for the client, they don t automatically add these tags; they simply send the contents 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 in just after the opening of the Page object s <form runat=server> element. RegisterClientScriptBlock is an ideal function to use to register blocks of dynamically created JavaScript functions that you plan to call later in your code:

 

Dim script As New System.Text.StringBuilder

With script

 .Append("<Script Language='JavaScript'>")

 .Append("function myFunction() {")

 .Append("alert('Hello ")

 .Append(TextBox1.Text)

 .Append("') }")

 .Append("</Script>")

End With

RegisterClientScriptBlock("myFunction", script.ToString)

 

In this code example I used server-side VB code to create JavaScript code on the fly and registered the script to be emitted to the client s browser. However, because we created a JavaScript function, this code will not get run by the browser until we call it. For that we can use either of the other two functions.

 

RegisterStartupScript

If we wanted this code to run as soon as the page was running, we could change it slightly to appear as follows:

 

Dim script As New System.Text.StringBuilder

With script

 .Append("<Script Language='JavaScript'>")

 .Append("function Page_Load() {")

 .Append("alert('Hello ")

  .Append(TextBox1.Text)

 .Append("') }")

 .Append("</Script>")

End With

RegisterStartupScript("startup", script.ToString)

 

In this example I tied the execution of the code to the page load event for the document. You don t have to do this; you could emit code that is run directly and not inside of a function. One thing to remember is that this code is emitted right before the closing tag for the Page object s <form runat=server> tag. Because this code is emitted, and any JavaScript not 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 could have some unintended results and errors. Hooking to the page load event is a safer approach.

 

RegisterOnSubmitStatement

The last of the three functions, RegisterOnSubmitStatement, is very similar. This method allows your code to access and tie to the OnSubmit event of the page. It s a good idea that any script you emit here should be a function call to client-side code that is registered somewhere else, either directly on the page or through a RegisterClientScriptBlock call.

 

You can put simple JavaScript into this method to have it execute, but in most cases you ll be using this method to install custom validation code or other more complex code to call before the processing of the page submit. This is easier to maintain and easier to read if it is in a separate JavaScript function.

 

Using these three very simple methods on the Page object you can easily create JavaScript code dynamically on the server side and register that script in a variety of ways to execute in the client s browser.

 

Brad McCabe is a consultant with Ajilon Consulting, a leading solutions provider. Brad also has been a systems architect and consultant for several Fortune 500 companies and has been a featured speaker at numerous Microsoft events around the world. His primary interests include ASP.NET, Tablet PC, .NET Compact Framework, and Microsoft s networking technologies. E-mail him at [email protected].

 

 

 

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish