Published: 08 Jan 2007
By: Xun Ding
Download Sample Code

ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and methods of working with JavaScript code. This article explores the enhancements and the various ways of injecting JavaScript programmatically into ASP.NET 2.0 pages.

Contents [hide]

The JavaScript with ASP.NET Pages Series

  • Part 1  ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and methods of working with JavaScript code. This article explores the enhancements and the various ways of injecting JavaScript programmatically into ASP.NET 2.0 pages.
  • Part 2 ASP.NET provides a number of ways of working with client-side script. This article explores the usage and drawbacks of ASP.NET script callbacks, and briefly presents a bird's view of ASP.NET AJAX.
  • Introduction

    In ASP.NET 1.x days, many client-side tasks, such as tracking mouse events, setting page focus, displaying/hiding a section of page, was not directly supported by asp.net. This is because ASP.NET applications are server-based; all web control events are handled on the server side. The constant round trips to and from server often slows down work processes, and the page-refreshing often ensured a web form would to lose its focus or its scroll position. Therefore programmers still rely on a multitude of JavaScript to keep web pages nimble and responsive. However, in ASP.NET 1.x, injecting JavaScript always involves two steps and quite some code: First, you weave your JavaScript function into a string in your code-behind page; second, you use the Page class of your web form to register the script, using either the Page.RegisterStartupScript or the Page.RegisterClientScriptBlock method.

    ASP.NET 2.0 has inherited some of the ASP.NET 1.x approaches of including JavaScript in a web form. Moreover, it has added many methods and properties to smooth and simplify the handling of some of the most common client-side tasks. It has also introduced new ways to include JavaScript on the server side or load JavaScript from resources. In this article will go into detail of the enhancements and the various ways of working with Script code in ASP.NET 2.0.

    Client-Side Enhancements

    In this section, we will consider three common client-side tasks that ASP.NET 2.0 have made as easy as setting properties of controls.

    1. Setting focus to web controls

    In ASP.NET 1.x, it is not possible to programmatically set focus to a web server control without a bit help from the JavaScript's function focus(). Here is how it was commonly done in C#:

    However, in ASP 2.0, there are three ways to dynamically set the focus to a specific control, all in just one line of code. You pass the control ID as the parameter and call the Page.SetFocus(control) method, which enables you to set the focus to a particular control immediately after a page is initiated or loaded.

    Or you can call the Focus method that is available to all web controls. You can call it in the Page_load event or based on a user's response to set up a skip pattern. For example, if you have a TextBox web control called Textbox1, you may simply call:

    ASP 2.0 also has a new property called DefaultFocus. By setting the DefaultFocus property, you can set the focus to a desired control when the page loads.

    For example, the code below will automatically set the focus on TextBox2 when the web form is loaded:

    2. Popping up Message Boxes

    Confirming with users before they take actions with potentially irreversible consequences like record deleting is a common practice, so is alerting users about important information with a JavaScript alert box. In ASP.NET 1.x, with either a delete column of a DataGrid, or a regular web control, we need to attach the JavaScript alert(msg) or confirm(msg) function to the control's attributes or register the script with the Page class.

    For example, we can use the following code to add the alert script to a button control:

    Or similarly we can attach the confirm(msg) script to a button.

    However, with a ASP.NET 1.x DataGrid, we need to place the code for the confirm messagebox in the DataGrid's OnItemDataBound or OnItemCreated event handler. The code below shows how this can be done in the OnItemDataBound event.

    In ASP.NET 2.0, to add a client-side message box is just a matter of setting the OnClientClick property, as the following:

    However, with the GridView, the approach is similar to that of ASP.NET 1.x in terms of adding a confirmation box before deleting a GridView row. That is, you have to attach the confirm() script to the attributes of the delete column. Only with ASP.NET 2.0, you need to place the confirmation script within the RowDataBound event handler.

    As an alternative, you can convert the CommandField to a TemplateField and add a Button with the onClientClick property set to the javascript confirm() function.

    3. Maintaining Page Scrolling Position

    In ASP 2.0, it is very easy to maintain a web page's scrolling position across postbacks. To achieve this, simply add the following page directive at the top of your webpage:

    However in ASP 1.x, it is not quite so simple, even though ASP.NET 1.x has a SmartNavigation page directive that supposedly enables you to achieve the same goal. But as noted in many online posts and publications, SmartNavigation has many known issues and it works only with Internet Explorer 5.5 or later. Several developers wrote some JavaScript code and wrapped the code inside a custom server control to work around the problem. For example, there is an article by Steve Stchur addressing this issue: Maintaining Scroll Position on Postback

    Injecting JavaScript Code

    ASP.NET 2.0 not only provides ways to simplify some of the most common client-side tasks, it also allows you to write and include your own JavaScript in a web form. There are three ways to do so:

    1. Injecting script blocks directly into a web page
    2. Including JavaScript on the server side
    3. Embedding JavaScript in Resources

    As mentioned above, in ASP.NET 1.x, to include script in a web page, you always have to take two steps:

    1. Define the JavaScript in a string variable
    2. Register it with the Page class

    In ASP.NET 2.0, there is a similar approach. However, instead of the Page class, it is recommended you register the script using the methods exposed by the ClientScript property of the Page class. ClientScript is an instance of a new ASP.NET 2.0 class called ClientScriptManager. Moreover, ClientScript has many new methods to work with JavaScript.

    Injecting Script blocks on demand

    Script blocks on demand are code that execute only if a code-specific event is triggered on the client side. To inject script blocks on demand, use ClientScript.RegisterClientScriptBlock. The following example shows how to pop up a new window when the button btnPopUp is clicked using the RegisterClientScriptBlock method:

    Startup Script Blocks

    Like the Page.RegisterStartupScript method with ASP.NET 1.x, ASP.NET 2.0 has ClientScript.RegisterStartupScript to execute JavaScript when the page first loads. The above example could be converted to:

    Including JavaScript on the server side

    You can also include external JavaScript files via codebehind. Let's say you have a JavaScript file called myJavaScript.js, and you would like include it inside the web form by using the RegisterClientScriptInclude method, as shown in the following example:

    This piece of code will inject the following JavaScript include in your html code generated by the server:

    Embedding JavaScript in Resources

    In ASP.NET 2.0, you can also add your JavaScript or image files or CSS stylesheet as embedded resources. However, to do so, you must create a custom control, add necessary scripts or files to the project, then set the files property of Build Action as an embedded resources, as illustrated in the following screenshot:

    For this article, I borrowed (however simplified) a custom control called AutoComplete Dropdownlist as an example. Briefly, to be able to access the JavaScript in the embedded resource, you need to take two steps: Declare the resource in the control's class file or in the AssemblyInfo.cs using the syntax:

    And in our example, it would be:

    By doing so, we mark the file as accessible through the WebResource.axd HTTP handler, then we may retrieve the actual file from the resources of the project's assembly by calling the method GetWebResourceUrl(type, webresource).

    Now we can inject the JavaScript or other resource file by using the RegisterClientScriptInclude method.

    Summary

    JavaScript is essential to keep web pages nimble and responsive. While ASP.NET 1.x has been cumbersome working with script, ASP.NET 2.0 has made great enhancements to remedy the limitations. It has made dealing with some of the most common client-side tasks as easy as setting control properties, and has introduced new classes and methods to allow injecting JavaScript into webforms more flexible.

    The JavaScript with ASP.NET Pages Series

  • Part 1  ASP.NET 2.0 has made quite a few enhancements over ASP.NET 1.x in terms of handling common client-side tasks. It has also created new classes, properties and methods of working with JavaScript code. This article explores the enhancements and the various ways of injecting JavaScript programmatically into ASP.NET 2.0 pages.
  • Part 2 ASP.NET provides a number of ways of working with client-side script. This article explores the usage and drawbacks of ASP.NET script callbacks, and briefly presents a bird's view of ASP.NET AJAX.
  • References

    Enhancing ASP.NET Pages with JavaScript
    Accessing Embedded Resources through a URL using WebResource.axd
    Client-Side Enhancements in ASP.NET 2.0
    An ASP.NET 2.0 AutoComplete DropDownList...
    Default Focus, Buttons and Validation Errors with ASP.NET 2.0
    Dino Esposito (2005): Programming Microsoft ASP.NET 2.0 Applications: Advanced Topics. Microsoft Press. ISBN: 978-0-7356-2177-0.

    <<  Previous Article Continue reading and see our next or previous articles Next Article >>

    About Xun Ding

    Web developer, Data Analyst, GIS Programmer

    This author has published 12 articles on DotNetSlackers. View other articles or the complete profile here.

    Other articles in this category


    Code First Approach using Entity Framework 4.1, Inversion of Control, Unity Framework, Repository and Unit of Work Patterns, and MVC3 Razor View
    A detailed introduction about the code first approach using Entity Framework 4.1, Inversion of Contr...
    jQuery Mobile ListView
    In this article, we're going to look at what JQuery Mobile uses to represent lists, and how capable ...
    Exception Handling and .Net (A practical approach)
    Error Handling has always been crucial for an application in a number of ways. It may affect the exe...
    JQuery Mobile Widgets Overview
    An overview of widgets in jQuery Mobile.
    Book Review: SignalR: Real-time Application Development
    A book review of SignalR by Simone.
    Top
     
     
     

    Discussion


    Subject Author Date
    placeholder Thanks - good article Jer OLo 3/19/2010 1:13 AM
    download not working m Fowle 2/27/2007 4:35 PM
    placeholder RE: download not working Sonu Kapoor 2/27/2007 5:23 PM
    Feedback Francesco Cavallaro 1/24/2008 5:03 AM
    placeholder it's very use full..Thanks a lot. ramki.ch 6/19/2008 7:41 AM
    Correction Steve Lawrence 5/9/2007 5:48 PM
    placeholder whoops. Steve Lawrence 5/9/2007 5:50 PM

    Please login to rate or to leave a comment.