Wednesday, November 19, 2008

Cheat sheet to create ASP.NET AJAX control

Recently I have done a project that required me to do some ASP.NET AJAX coding. It is relatively straightforward to create a customer AJAX control once I got familiar with the whole pattern. But just when I felt comfortable, I started to forget some of the minor details. So I created a cheat sheet. Here it is:

* Suppose you have installed AJAX extension and have all the ASP.NET project ready to go in Visual studio:

  1. Create a the javascript file by registering the namespace, defining a class body, and registering the class. This contains the meat of the AJAX behavior.
    For example:
    Type.registerNamespace("my.controls");
    my.controls.customcontrol = function(element) {...} my.controls.customcontrol.prototype = {...}
    my.controls.customcontrol.registerClass(
    "my.controls.customcontrol",
    sys.UI.Control
    );

  2. Change the "Build action" of the javascript as "Embedded as resource" so that the script is embedded into the assembly.
  3. Add an assembly level attribute in the project to expose the javascript as Web resource, so that ASP.NET can locate it in the assembly.
    For example:
    [assembly : WebResource("AssemblyName.control.js", "text/javascript")]
  4. Create a matching C# class that inherits from ScriptControl base class.
    You need to the following two methods:

    GetScriptDescriptors():
    This method returns data describing the mapping of C# property value to the corresponding javascript properties.

    GetScriptReferences(): This method returns all the javascript that needs to be delivered to the client side when "rendering" this AJAX control. The javascript file created earlier should be included as a reference.

    This step integrates the delivery of the AJAX javascript into the existing ASP.NET page life cycle. When the ASP.NET renders this control in an .aspx page, the ScriptControl class will render out the proper <script> element based on what these two methods return (instead of outputing HTML)

As you can see, there are a few steps to glue the javascript into the ASP.NET pipeline. Now you can use the AJAX control the same way as the normal ASP.NET controls. But finally, you must have <ScriptManager> element on the page in order for the AJAX control to work. :)

No comments: