7.4 Respond to Client-Side Events with JavaScript


Problem

You need to add client-side JavaScript code to a Web form.

Solution

Define the JavaScript function in a string, and use the Page.RegisterClientScriptBlock method to add the JavaScript function to the rendered page. You can then add control attributes that call the functions.

Discussion

ASP.NET includes a rich programming model. Unfortunately, once a page is rendered to HTML, you can't execute any more .NET code without first triggering a postback to the server. This limitation greatly reduces the effectiveness of validation code and other niceties that can support polished interactive Web pages.

Of course, there's no reason that you can't mingle client-side JavaScript functionality with your .NET code. Although .NET doesn't include any object interface for creating JavaScript, you can manually inject it into the page. One way to do this is simply to set a control attribute. For example, you can create a text box that displays a message box when it loses focus by including the following JavaScript code:

 TextBox1.Attributes.Add("onBlur", "alert('The text box has lost focus!');"); 

The TextBox tag will be rendered to HTML like this:

 <input name="TextBox1" type="text" id="TextBox1"  onBlur="alert('The text box has lost focus!');"  ... /> 

In this case, you're using the built-in JavaScript alert function and the JavaScript onBlur event, which fires when a control loses focus. Most HTML elements support a small number of events, and some of the most useful include the following:

  • onFocus Occurs when a control receives focus

  • onBlur Occurs when focus leaves a control

  • onClick Occurs when the user clicks a control

  • onChange Occurs when the user changes the value of certain controls

  • onMouseOver Occurs when the user moves the mouse pointer over a control

Another approach to adding JavaScript code is to define a JavaScript function in a .NET string variable and then to instruct ASP.NET to insert it into the rendered Web form where it can be used. If you follow this approach, any control can call the function in response to a JavaScript event.

The following example demonstrates this technique with a simple Web page that includes a table and an image (shown in Figure 7.2). As the user moves the mouse over the cells in the table, two custom JavaScript functions are used, one that highlights the current cell and one that removes the highlight from the previous cell. In addition, the highlighting function changes the image URL depending on which table column is currently selected. If the user hovers the mouse over the first column, an animated GIF of a happy face is shown. If the user hovers the mouse over the second or third column, an animated GIF of a book with a flashing question mark is shown instead.

 using System; using System.Web; using System.Web.UI.WebControls; public class JavaScriptTest : System.Web.UI.Page {     protected System.Web.UI.WebControls.Table Table1;     protected System.Web.UI.WebControls.Image Image1;     // (Designer code omitted.)     private void Page_Load(object sender, System.EventArgs e) {         // Define the JavaScript functions.         string highlightScript =              "<script language=JavaScript> " +             "function HighlightCell(cell) {" +             "cell.bgColor = '#C0C0C0';" +             "if (cell.cellIndex == 0)"+             "{document.Form1.Image1.src='happy_animation.gif';}"+             "else {document.Form1.Image1.src='question_animation.gif';}" +             ";}" +             "</script>";         string unhighlightScript =              "<script language=JavaScript> " +             "function UnHighlightCell(cell) {" +             "cell.bgColor = '#FFFFFF';" +             "}" +             "</script>";         // Insert the function into the page (it will appear just after         // the <form runat=server> tag.         // Note that each script block is associated with a string name.         // This allows multiple controls to register the same script block,         // while ensuring it will only be rendered in the final page once.         if (!this.IsClientScriptBlockRegistered("Highlight")) {             Page.RegisterClientScriptBlock("Highlight", highlightScript);         }         if (!this.IsClientScriptBlockRegistered("UnHighlight")) {             Page.RegisterClientScriptBlock("UnHighlight", unhighlightScript);         }         // Set the attributes of every cell in the table.         foreach (TableRow row in Table1.Rows) {             foreach (TableCell cell in row.Cells) {             cell.Attributes.Add("onMouseOver", "HighlightCell(this);");             cell.Attributes.Add("onMouseOut", "UnHighlightCell(this);");         }     } } 
click to expand
Figure 7.2: A JavaScript function that highlights the current cell.
Note  

It's important to understand the security implications of JavaScript code. All JavaScript code is rendered directly in the HTML of the page. Therefore, you should assume that the user can examine it, and you should never include any secret algorithms or information in your code. Furthermore, you should use JavaScript validation code as a nicety, not as a way to prevent invalid actions, because users might be able to disable or circumvent JavaScript in their browsers.

You can find numerous sites on the Internet that provide JavaScript tutorials and sample code. In addition, a full JavaScript reference is provided by Netscape at http://devedge.netscape.com/library/manuals .




C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

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