Professional VB 2005 with .NET 3.0 (Programmer to Programmer)

Developers generally like to include some of their own custom JavaScript functions in their ASP.NET pages. You have a couple of ways to do this. The first is to apply JavaScript directly to the controls on your ASP.NET pages. For example, the following simple Label server control displays the current date and time:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) TextBox1.Text = DateTime.Now.ToString() End Sub

This little bit of code displays the current date and time on the page of the end user. The problem is that the date and time displayed are correct for the Web server that generated the page. If the user is in the Pacific time zone (PST) and the Web server is in the Eastern time zone (EST), the page won’t be correct for that viewer. If you want the time to be correct for anyone visiting the site, regardless of where they reside in the world, then you can employ JavaScript to work with the TextBox control:

<%@ Page Language="VB" %> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Using JavaScript</title> </head> <body onload="javascript:document.forms[0]['TextBox1'].value=Date();"> <form runat="server"> <div> <asp:TextBox Runat="server" Width="300"></asp:TextBox> </div> </form> </body> </html>

In this example, even though you are using a standard TextBox server control from the Web server control family, you can access this control using JavaScript that is planted in the onload attribute of the <body> element. The value of the onload attribute actually points to the specific server control via an anonymous function by using the value of the ID attribute from the server control: TextBox1. You can get at other server controls on your page by employing the same methods. This bit of code produces a text box with the current date and time inside of it.

ASP.NET uses the new Page.ClientScript property to register and place JavaScript functions on your ASP.NET pages. Three of these methods are reviewed here. Other methods and properties are available through the ClientScript object (which references an instance of System.Web.UI.ClientScriptManager), but these are the most useful ones. You can find the rest in the SDK documentation.

Tip 

The Page.RegisterStartupScript and Page.RegisterClientScriptBlock methods from the .NET Framework 1.0/1.1 are now considered obsolete. Both of these options for registering scripts required a key/script set of parameters. Because two separate methods were involved, key name collisions were very likely. The Page.ClientScript property is meant to bring all the script registrations under one umbrella, making your code less error prone.

Using Page.ClientScript.RegisterClientScriptBlock

The RegisterClientScriptBlock method enables you to place a JavaScript function at the top of the page. This means that the script is in place for the startup of the page in the browser. Its use is shown here:

<%@ Page Language="VB" %> <script runat="server"> Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myScript As String = "function AlertHello() { alert('Hello ASP.NET'); }" Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MyScript", _ myScript, True) End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Adding JavaScript</title> </head> <body> <form runat="server"> <div> <asp:Button Runat="server" Text="Button" OnClientClick="AlertHello()" /> </div> </form> </body> </html>

You create the JavaScript function AlertHello() as a string called myScript. Then, using the Page.ClientScript.RegisterClientScriptBlock method, you program the script to be placed on the page. The two possible constructions of the RegisterClientScriptBlock method are as follows:

The preceding example specifies the type as Me.GetType(), the key, the script to include, and then a Boolean value setting of True so that .NET places the script on the ASP.NET page with <script> tags automatically. When running the page, you can view the source code for the page to see the results:

<html xmlns="http://www.w3.org/1999/xhtml" > <head><title> Adding JavaScript </title></head> <body> <form method="post" action="JavaScriptPage.aspx" > <div> <input type="hidden" name="__VIEWSTATE" value="/wEPDwUKMTY3NzE5MjIyMGRkiyYSRMg+bcXi9DiawYlbxndiTDo=" /> </div> <script type="text/javascript"> <!-- function AlertHello() { alert('Hello ASP.NET'); }// --> </script> <div> <input type="submit" name="Button1" value="Button" onclick="AlertHello();" /> </div> </form> </body> </html>

From this, you can see that the script specified was indeed included on the ASP.NET page before the page code. Not only were the <script> tags included, but the proper comment tags were added around the script (so older browsers will not break).

Using Page.ClientScript.RegisterStartupScript

The RegisterStartupScript method is similar to the RegisterClientScriptBlock method. The big difference is that the RegisterStartupScript places the script at the bottom of the ASP.NET page instead of at the top. In fact, the RegisterStartupScript method even takes the same constructors as the RegisterClientScriptBlock method:

What difference does it make where the script is registered on the page? A lot, actually! If you have a bit of JavaScript that is working with one of the controls on your page, in most cases you want to use the RegisterStartupScript method instead of RegisterClientScriptBlock. For example, you would use the following code to create a page that includes a simple <asp:TextBox> control that contains a default value of Hello ASP.NET:

<asp:TextBox Runat="server">Hello ASP.NET</asp:TextBox>

Then use the RegisterClientScriptBlock method to place a script on the page that utilizes the value in the TextBox1 control:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myScript As String = "alert(document.forms[0]['TextBox1'].value);" Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "myKey", myScript, _ True) End Sub

Running this page results in the JavaScript error shown in Figure 19-16.

Figure 19-16

The error occurs because the JavaScript function fired before the text box was even placed on the screen. Therefore, the JavaScript function did not find TextBox1, which caused an error to be thrown by the page. Now try the RegisterStartupScript method shown here:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Dim myScript As String = "alert(document.forms[0]['TextBox1'].value);" Page.ClientScript.RegisterStartupScript(Me.GetType(), "myKey", myScript, _ True) End Sub

This approach puts the JavaScript function at the bottom of the ASP.NET page, so when the JavaScript actually starts, it finds the TextBox1 element and works as planned, as shown in Figure 19-17.

Figure 19-17

Using Page.ClientScript.RegisterClientScriptInclude

The final method is RegisterClientScriptInclude. Many developers place their JavaScript inside a .js file, which is considered a best practice because it makes it very easy to make global JavaScript changes to the application. You can register the script files on your ASP.NET pages through the use of the RegisterClientScriptInclude method, shown here:

Dim myScript As String = "myJavaScriptCode.js" Page.ClientScript.RegisterClientScriptInclude("myKey", myScript)

This creates the following construction on the ASP.NET page:

<script src="/books/2/382/1/html/2/myJavaScriptCode.js" type="text/javascript"></script>

Категории