Lesson 4: Using Client-Side Scripts

Lesson 4: Using Client-Side Scripts

ASP.NET provides a full set of programming tools for creating Web applications that run on servers, so why should you worry about adding scripts to run on the client s computer? Because scripts have direct access to the client s browser, they make it possible to do many things you can t do from server-side code. For example, you can use client-side scripts to perform the following tasks:

  • Control the browser window.

    You can t control the browser from server-side code. To open new windows, set focus within a window, navigate between frames, navigate within history, and perform other browser-related tasks, you must use client-side scripts.

  • Respond immediately to mouse-over events.

    Server-side code can respond to events only after the page is posted back to the server; client-side code can respond to page events as they occur.

  • Start the client s mail system.

    You can send mail from the client using the Mailto protocol. Additionally, you can send mail from the server using the SmtpMail class.

In this lesson, you ll learn how to add scripts to Web forms and HTML pages in Visual Studio to create code that executes on the client s computer.

After this lesson, you will be able to

  • Test a browser to see whether it can run scripts

  • Choose a scripting language that suits your needs

  • Use objects provided by the Document Object Model (DOM) to control the browser window and the documents it contains

  • Create scripts that run inline as the page is interpreted by the browser

  • Create scripts that respond to events in the browser, such as mouse clicks and mouse-move events

  • Get input from the user and display a response using scripts

  • Send mail from either the client or server

Estimated lesson time: 30 minutes

Before You Use Scripts

Client-side scripts pose three issues you should be aware of:

  • Not all browsers support scripting.

  • Only Microsoft Internet Explorer supports VBScript.

  • Scripting poses security concerns.

Because not all browsers support scripts, you should check the browser capabilities before displaying pages that contain client-side scripts. The following Page_Load event procedure checks whether a browser supports scripts and redirects users to a page recommending they download a new version if their browser does not support scripts:

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load If Request.Browser.VBScript Then Response.Redirect("VBScripts.htm") Exit Sub ElseIf Request.Browser.JavaScript Then Response.Redirect ("JScripts.htm") Else Response.Redirect("NoScripts.htm") End If End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { if (Request.Browser.VBScript) Response.Redirect("VBScripts.htm"); else if (Request.Browser.JavaScript) Response.Redirect("JScripts.htm"); else Response.Redirect("NoScripts.htm"); }

Another concern with client-side scripts is security. There are two aspects to this issue. First, your scripts are not secure they can be viewed or copied by anyone visiting your application. Second, scripts can potentially spread viruses; therefore, some users set their browser security settings to disable scripts.

The Browser object s VBScript and JavaScript properties will return True, even if scripting has been disabled. To check whether scripting is enabled, you need to be a little clever. The following HTML tests whether scripting is enabled by trying to run a script. If scripting is enabled, the user is redirected to another page and he or she never sees the message that follows the script.

<html> <script> window.navigate("scripts.aspx") </script> <!-- If scripting is enabled, the following is never displayed --> <head> <title>Scripts</title> </head> <body MS_POSITIONING="FlowLayout"> <h2>Scripting is turned off.</h2> <p>Your Internet security options specify that your browser will not run scripts, and therefore you cannot view the page you requested. To turn scripting on, reset your browser's Internet security options to Medium, or enable active scripting in the custom security settings.</p> <p><a href="CheckBrowser.htm">Click here</a> to try again.</p> </body> </html>

Choosing a Scripting Language

Client-side scripts can be written in either VBScript or JScript. Scripting languages have the following differences from compiled languages, such as Visual Basic .NET or Visual C#:

  • Script languages are not compiled.

    Instead, they are interpreted by the browser at run time.

  • Script keywords are a safe subset of their parent languages.

    Scripts don t allow you to create or delete files on the user s disk or to perform tasks that obviously risk crashing the user s computer.

Both VBScript and JScript are functionally equivalent they differ only in syntax and keywords. In general, Visual C# programmers are more comfortable using JScript because it follows the C conventions; Visual Basic programmers are more comfortable using VBScript because it is closely related to Visual Basic. However, only Internet Explorer supports VBScript, so if your application needs to run on other browsers, you should use JScript.

If you are a Visual Basic programmer, you will probably not like the fact that JScript is case sensitive. In JScript, all keywords, variables, object references, methods, and properties must be correctly capitalized in order to work.

For more information about the scripting languages, see the following Visual Studio online Help topics:

  • JScript User s Guide

  • JScript Language Reference

  • VBScript User s Guide

  • VBScript Language Reference

Understanding the DOM

The Document Object Model (DOM) is made up of the objects that the browser provides for scripting. These objects let you control the browser window, the current page (or document), and objects on the page. Figure 7-7 shows the objects provided by the DOM.

figure 7-7 the dom object hierarchy

Figure 7-7. The DOM object hierarchy

Explaining all the objects in the DOM is outside the scope of this book. However, a great deal of information is available in the Visual Studio online Help in the DHTML References topic. That topic and the references it links to are part of the Web Workshop online Help.

Adding Inline Scripts

Web pages can include scripts inline as part of their content or as procedures that run in response to events. Inline scripts run the moment the browser encounters them. The example in the preceding section shows how this works by redirecting the browser to a new page if the browser allows scripting:

<html> <script> window.navigate("scripts.aspx") </script> <!-- If scripting is enabled, the markup that follows this code is never displayed --> <head> <title>Scripts</title> </head> <body MS_POSITIONING="FlowLayout" onunload="return window_onunload()"> <h2>Scripting is turned off.</h2> <p>Your Internet security options specify that your browser will not run scripts, and therefore you cannot view the page you requested. To turn scripting on, reset your browser's Internet security options to Medium, or enable active scripting in the custom security settings.</p> <p><a href="CheckBrowser.htm">Click here</a> to try again.</p> </body> </html>

If this script successfully runs, the user never sees the message that scripting is turned off because the script runs before any page content. If an inline script refers to an element on the page, that element must appear before the script refers to it. For example, the following HTML displays two text boxes and uses a script to move the cursor to the second text box:

VBScript

<HTML> <body language="vbscript"> <form  method="post" runat="server"> <P> <asp:TextBox  Runat="server"></asp:TextBox> </P> <P> <asp:TextBox  Runat="server"></asp:TextBox> </P> <script>window.document.all("txtLastName").focus()</script> </form> </body> </HTML>

JScript

<HTML> <body language="javascript"> <form  method="post" runat="server"> <P> <asp:TextBox  Runat="server"></asp:TextBox> </P> <P> <asp:TextBox  Runat="server"></asp:TextBox> </P> <script>window.document.all["txtLastName"].focus()</script> </form> </body> </HTML>

Inline scripts can also be used as attributes of HTML elements that perform actions, such as the HTML Button control. For example, the following HTML creates a button that opens a Help page in a new window:

<button  onclick="window.open('help.aspx', 'help', 'height=200,width=300')">Help</button>

Notice that the preceding inline script is language-neutral in other words, it will work whether the language attribute of the <body> element is set to VBScript or JScript. To use a scripting language other that the one set in the <body> element, you need to set the <script> element s language attribute. For example, the following scripts display a list of heading levels:

VBScript

<HTML> <script language="vbscript"> For i = 1 to 6 document.write("<h" & i & ">") document.write("H" & i) document.write("</h" & i & "><br>") Next </script> </HTML>

JScript

<HTML> <script language="javascript"> for (i = 1; i <= 6; i++) { document.write("<h" + i + ">"); document.write("H" + i); document.write("</h" + i + "><br>"); } </script> </HTML>

The preceding code displays the six HTML heading levels, as shown in Figure 7-8.

figure 7-8 inline scripts

Figure 7-8. Inline scripts

Responding to Events with Script Procedures

Scripts also define procedures that respond to page events, such as the window loading, the buttons being clicked, and the mouse passing over objects.

To create a script event procedure, follow these steps:

  1. Using Visual Studio, create or open the page for which you want to include the client-side scripts. The page can be a Web form (.aspx) or an HTML page (.htm).

  2. Switch to the HTML view of the page.

  3. From the drop-down list at the top left of the page, select the object for which you want to add the event procedure, as shown in Figure 7-9.

    figure 7-9 selecting the object

    Figure 7-9. Selecting the object

  4. From the drop-down list at the top right of the page, select the event that you want the code to respond to, as shown in Figure 7-10.

    figure 7-10 selecting the event

    Figure 7-10. Selecting the event

Visual Studio creates a script block containing an empty event procedure, as shown in the following code:

VBScript

<script id=clientEventHandlersVBS language=vbscript> <!-- Sub butRunScript_onmouseover End Sub --> </script>

JScript

<script id=clientEventHandlersJS language=javascript> <!-- function butRunScript_onmouseover() { } //--> </script>

Any code you add to the event procedure will run when that page event occurs. For example, the following code switches the mouse cursor to the hand symbol when the user moves the mouse over the button:

VBScript

Sub butRunScript_onmouseover butRunScript.style.cursor = "hand" End Sub

JScript

function butRunScript_onmouseover() { // Display the Hand cursor when the mouse moves over the button. butRunScript.style.cursor = "hand"; }

Client-side event procedures can detect a wide variety of events, including keypresses, mouse-over events, clicks, loads, and unloads. Unlike server-side events, client-side events do not provide arguments directly. Instead, you use the window object s event method to get values. For example, the following mousemove event procedure displays the coordinates of the cursor in the browser s status bar:

VBScript

Sub document_onmousemove ' Display X, Y coordinates as the mouse moves across the browser window. window.status = window.event.clientX & ", " & window.event.clientY End Sub

JScript

function window_onmousemove() { // Display X, Y coordinates as the mouse moves across the browser window. window.status = window.event.clientX + ", " + window.event.clientY; }

The code in client-side event procedures can get and set the values displayed in server and HTML controls on the page. This means that you can get values from the user and provide responses without posting the page back to the server. For example, the following HTML code defines a page that plays a simple game with the user all without posting back to the server:

VBScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>EventScript</title> <meta name="vs_defaultClientScript" content="VBScript"> <meta name="vs_targetSchema"  content="http://schemas.microsoft.com/intellisense/ie5"> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="ProgId" content="VisualStudio.HTML"> <meta name="Originator" content="Microsoft Visual Studio.NET 7.0"> <script  language="vbscript"> Sub butRunScript_onclick ' Display a message in a text area. sMessage = "I am thinking of a number between 0 and 9. "  sMessage = sMessage & "Press a number key to take a guess." txtMessage.value = sMessage ' Initialize the random number generator. Randomize ' Get a random number and store it in a hidden field. hidNumber.value = Int(9 * Rnd) End Sub Sub document_onkeypress ' If the keypress matches the number, display a success message. if (window.event.keyCode - 48) = CInt(hidNumber.value) then txtMessage.value = "You guessed it!" ' Otherwise tell the correct answer. else txtMessage.value = "You didn't guess it. It was: " & hidNumber.value end if End Sub </script> </head> <body MS_POSITIONING="FlowLayout"> <p> <textarea ></textarea> </p> <P> <INPUT type="button"  value="Run Script"  NAME="butRunScript"> </P> <INPUT  type="hidden" name="Hidden1"> </body> </html>

JScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <HTML> <HEAD> <META NAME="GENERATOR" Content="Microsoft Visual Studio 7.0"> <TITLE></TITLE> <meta name="vs_defaultClientScript" content="JavaScript"> <meta name="vs_targetSchema"  content="http://schemas.microsoft.com/intellisense/ie5"> <meta name="GENERATOR" content="Microsoft Visual Studio.NET 7.0"> <meta name="ProgId" content="VisualStudio.HTML"> <meta name="Originator" content="Microsoft Visual Studio.NET 7.0"> <script id=clientEventHandlersJS language=javascript> <!-- function window_onkeypress() { // If the keypress matches the number, display a success message. if ((window.event.keyCode - 48) == parseInt(hidNumber.value)) txtMessage.value = "You guessed it!"; // Otherwise tell the correct answer. else txtMessage.value = "You didn't guess it. It was: " + hidNumber.value; } function butRunScript_onclick() { // Display a message in a text area. sMessage = "I am thinking of a number between 0 and 9. "  + "Press a number key to take a guess."; txtMessage.value = sMessage; // Get a random integer. hidNumber.value = Math.round(9 * Math.random()); } //--> </script> </HEAD> <BODY language=javascript onmousemove="return window_onmousemove()" onkeypress="return window_onkeypress()"> <p> <textarea  style="WIDTH: 200px; HEIGHT: 88px" rows="5" cols="22" NAME="txtMessage"></textarea> </p> <P> <INPUT type="button"  value="Run Script"  NAME="butRunScript" language=javascript onmouseover="return butRunScript_onmouseover()" onclick="return butRunScript_onclick()"> </P> <P><INPUT  type="hidden" name="Hidden1"></P> </BODY> </HTML>

At run time, the preceding code displays a page that plays a guessing game, as shown in Figure 7-11.

figure 7-11 the guessing game

Figure 7-11. The guessing game

Sending Mail

To send mail using the client s mail system, create a hyperlink using the Mailto protocol. For example, the following HTML shows a hyperlink that creates a new message with a subject line and a short message body:

<A href="mailto:someone@microsoft.com?SUBJECT=Sending from a client&BODY=Some message text.">

When the user clicks this hyperlink, the client s browser starts the client s mail application and creates a message. You can use the Mailto protocol in place of any destination URL in a server control or an HTML control. For instance, the following HTML defines a Hyperlink server control that sends a mail message:

<asp:HyperLink  NavigateUrl="mailto:someone@microsoft.com? SUBJECT=Mailing a Webform&amp;BODY=Some message text."  Runat="server">Send mail.</ asp:HyperLink>

To send mail from the server, use the SmtpMail class from server-side code. The SmtpMail class does not start the client s mail system to allow the user to compose the message to send, to add attachments, or to validate addresses. Instead, you compose the message in code and send it one of two ways:

  • You can send a simple message using the SmtpMail class s Send method.

  • You can create a more complex message using the MailMessage class and then send that message using the SmtpMail class s Send method.

Both the SmtpMail class and the MailMessage class are part of the System.Web.Mail namespace in the .NET Framework, so add the following statement at the beginning of your module to simplify references to those classes in code:

Visual Basic .NET

Imports System.Web.Mail

Visual C#

using System.Web.Mail;

You don t need to create an instance of the SmtpMail class before using it. To send a simple message, just use the Send method, as shown here:

Visual Basic .NET

SmtpMail.Send ("someone@microsoft.com", "jesse@contoso.com",  "Subject line", _  "Message text.")

Visual C#

SmtpMail.Send("someone@microsoft.com", "jesse@contoso.com", "Subject line",  "Message text.");

The preceding line of code immediately sends a message from someone@microsoft.com to jesse@contoso.com. Both the from and to addresses are required, although they are not validated by the Send method. The SmtpMail class sends mail using your local SMTP server by default. To use a different server, set the SmtpServer property.

Using the Send method alone is fine for simple text messages, but to send a formatted message or a message containing an attachment, you need to create an object based on the MailMessage class and then use the SmtpMail class s Send method to send the message, as shown in the following code:

Visual Basic .NET

Private Sub butMail_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butMail.Click ' Create the message. Dim mailNew As New MailMessage() ' Set the message properties. mailNew.From = "someone@microsoft.com" mailNew.To = "jesse@contoso.com" mailNew.Subject = "This is the subject text." mailNew.Body = "This is the message text." ' Create an attachment. Dim atcItem As New _ MailAttachment(Server.MapPath(".") & "\joey.jpg") ' Attach it to the message. mailNew.Attachments.Add(atcItem) ' Send the message. SmtpMail.Send(mailNew) End Sub

Visual C#

private void butSendMail_Click(object sender, System.EventArgs e) { // Create the message. MailMessage mailNew = new MailMessage(); // Set the message properties. mailNew.From = "someone@microsoft.com"; mailNew.To = "jesse@contoso.com"; mailNew.Subject = "This is the subject text."; mailNew.Body = "This is the message text."; // Create an attachment. MailAttachment atcItem = new MailAttachment (Server.MapPath(".") +  "\\joey.jpg"); // Attach it to the message. mailNew.Attachments.Add(atcItem); // Send the message. SmtpMail.Send(mailNew); }

This code creates a message, sets the message properties, attaches a file to the message, and sends the message. As with the previous Send method example, the From and To properties are required but are not validated.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net