{infiniteZest}
// Articles. Tutorials. Utilities.
Home  |   Search  |   Login  
Categories Skip Navigation Links
New / All
AJAX
Apple
ASP.NET
.NET
Git
Google / Android
Python / IronPython
Miscellaneous
SQL Server
Incorporating ASP.NET AJAX into existing Custom Controls and JavaScript files
Summary
Since JavaScript has been supported by every major web browser for a long time now, every decent-sized web site uses some JavaScript. Now that ASP.NET AJAX is available, you might want to refactor and start adding some of the functionality available in these libraries. This article goes through the initial refactoring steps.
 
Table of Contents

Figure 1. Adding ASP.NET AJAX to existing projects

Add ASP.NET AJAX infrastructure

Add ScriptManager

Check for ScriptManager

Listing 1. Checking for the existence of ScriptManager

Remove Browser Detection Code

Detecting the browser up-front

Doing the feature testing

Use the Shortcuts from ASP.NET AJAX

Use ASP.NET AJAX Event Handling Methods

Next Steps …

Related Articles

 

It’s pretty likely that you have some JavaScript files used on your site or in your custom controls, etc. Now that you have added MS AJAX libraries to your site, you want to add those capabilities slowly to your existing JavaScript files.

So, now you want to refactor your existing JavaScript files little bit at a time – not so much as to cause headaches. Following are some suggestions.

Figure 1. Adding ASP.NET AJAX to existing projects

Adding ASP.NET AJAX to existing projects

Add ASP.NET AJAX infrastructure

First step is to add the ASP.NET AJAX (MS AJAX) infrastructure to your site/page. This, at the most fundamental level, mean adding ScriptManager control to the page where your own custom control or JavaScript is used.

Add ScriptManager

So, the very first step would be to add ScriptManager to the page. This could come from the Master Page or you can add it to the page under consideration. For ASP.NET AJAX to be enabled, there must be one and only one instance of the ScriptManager on the given page. If your site is already ASP.NET AJAX-enabled, then you don’t need to add this again.

So, within the <form></form> tags, add the ScriptManager control:

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>

If are not going to further manipulate ScriptManager on your page, this declaration can be as simplified as the following:

    <asp:ScriptManager runat="server" />

If your custom control already knows where to get the JavaScript files, adding the above will bring the client side JavaScript files from the ASP.NET AJAX library. So, you can start using the functionality from there.

Check for ScriptManager

If you are going to rely upon the ASP.NET AJAX capabilities in your custom control, you need to make sure there is a ScriptManager on the current page. There is a static method called GetCurrent() in the ScriptManager class. This method returns the current instance of the ScriptManager.

You would need to check for the existence of ScriptManager from your custom control, before proceeding too far. Perhaps, the best place could be in OnPreRender handler of your custom control.

Listing 1. Checking for the existence of ScriptManager

protected override void OnPreRender(EventArgs e)
{
    // Get the ScriptManager
    if (ScriptManager.GetCurrent(this.Page) == null)
        throw (new Exception("ASP.NET AJAX Required. Please add ScriptManager to the page."));

    //ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
    //if (scriptManager == null)
    //    throw (new Exception("ASP.NET AJAX Required. Please add ScriptManager to the page."));

 // Other stuff here
}

As shown above, you can try to get the current ScriptManager and throw an exception if it’s not there. The commented out portion shows it in an elaborate way – assigning the ScriptManager to a variable and checking whether it’s null or not. If you are going to do something more with this variable further down in that method you can use the commented out code.

Remove Browser Detection Code

It is very likely that you have some browser detection code in your old JavaScript files. There are a couple of different ways of doing this, and in most of the cases, this code can be removed.

Detecting the browser up-front

Typically, this would some piece of code that checks the userAgent string on the Navigator object. By using indexOf on the userAgent string you will look for the strings ‘Safari’, ‘Opera’, ‘Gecko’, etc. If something like navigator.userAgent.indexOf(‘Safari’) is true, then it is a Safari browser. In the old days, there used be a lot of checks on what properties document object supports (all, layers, etc.) – and based on this and the above, the browser would be established.

Typically, this code can be replaced by:

  • Checking whether it’s a supported browser on the server side and if it’s not supported, just not proceed with showing the custom control.
  • Doing the feature testing, as discussed in the next section.

If you need to check the browser on the client-side, see the following article:

Browser Detection from the Client-Side in ASP.NET AJAX

You can detect the browser on the server side by using the class HttpBrowserCapabilities:

HttpBrowserCapabilities thisBrowser = Page.Request.Browser;
if ((thisBrowser.Browser == "IE") && (thisBrowser.MajorVersion >= 6.0))
...

Doing the feature testing

This is used at the time of using a particular feature. For example, addEventListener is used by FireFox for adding event handlers, where as attachEvent is used by IE. So, just before adding event handlers, you will see if these methods are available on that particular element – for example: if (elem.addEventListener) … add the event listener for FireFox, and so on.

Even this feature checking code can be replaced by using the functionality in ASP.NET AJAX (which does this feature checking for us). For example, the event handling mechanisms of individual browsers can be replaced by the event handling mechanism of ASP.NET AJAX (discussed in a section below).

Use the Shortcuts from ASP.NET AJAX

ASP.NET AJAX client side library provides a few global short cuts for the most commonly used JavaScript DOM methods. The most commonly used method is document.getElementById, which is used to get the HTML Id by specifying its Id.

If you are using the complete document.getElementById each time you are getting an HTML element, you can replace that long string with $get global short cut from ASP.NET AJAX (it’s very possible that you have your own shortcut for this or if you used some other client side library like Prototype, you might have used something like $ as a replacement for document.getElementById).

For example, the following line:

document.getElementById(’mainbar’).style.display = ’inline’

Can be replaced with

$get(’mainbar’).style.display = ’inline’

Following additional global shortcuts are also available: $find, $create, and the event handler short cuts ($addHandler, $removeHandler, $addHandlers, $clearHandlers) that we discuss below.

Use ASP.NET AJAX Event Handling Methods

There are four event handling shortcuts, as mentioned above. The existing event handling code can be changed to use these short cuts.

For example, the following code that works for FireFox:

GetBox().contentWindow.document.addEventListener("mouseup",SelChanged,false);

Can be changed to the following:

$addHandler(GetBox().contentWindow.document, ’mouseup’, SelChanged);

Next Steps …

Various changes discussed above are the first steps towards migrating existing JavaScript code to use the ASP.NET AJAX libraries. From here on, a lot of additional changes can be made to the js files – adding namespaces, placing the existing code into classes, etc.

Related Articles

Browser Detection from the Client-Side in ASP.NET AJAX

How does an MS AJAX extender control get initialized on the client side?

The structure and usage of AutoCompleteExtender control

JavaScript files with RegisterClientScriptInclude and ScriptManager

Embedding JavaScript files in your custom controls

Bookmark and Share This

More Articles With Similar Tags
icon-ajax-browser-detection.jpg
ASP.NET AJAX client side libraries provide a Sys.Browser class. This class along with objects like Sys.Browser.InternetExplorer can be used to detect the browser that the current page is running on. This article discusses the browser detection from the client side.
icon-ms-ajax-validation.jpg
Since JavaScript is a loosely-typed language, type checking is not done for you automatically. If you are writing library-type functions (those that would be used by other developers), it is very useful to validate the parameters. Here is how MS AJAX does the parameter validation.
icon-ajax-char-counting.jpg
It would be very useful to have counter right next to the textbox and increase that number as the user is typing into that textbox. Based on the lengths of the string entered into the textbox we could change the background of the textbox (white, yellow, red). This can be done in JavaScript (on MS AJAX) with relatively a few lines of client-side code.
icon-extender-class-hierarchy.jpg
This article looks at how a control written with MS AJAX gets initialized on the client side. Discusses the JavaScript methods from the client-side library that get called in the initialization of the control. The example used here is the creation of an instance an autocompleteextender control.
icon-ajax-sys-namespaces.jpg
This article looks at how Microsoft AJAX library adds (‘simulates’) the namespace functionality. Understanding this not only lets you create namespaces in your client-side JavaScript code, but also helps you debug the client-side code effectively.
About  Contact  Privacy Policy  Site Map