My fantastic Webdings Logo

Reamped.NET

It's not that bad


Creating ASP.NET Ajax Aware Server Controls

Lately, I have been having to deal with finding ASP.NET Ajax when creating server controls. It is actually quite simple to do, and I think that if you are going to be coding server controls for ASP.NET you should definitely know how to do it. So in this post, we will go through embedding a javascript file into your assembly and then registering it to the page. Then I will show you how to find out if ASP.NET Ajax is loaded during the script registration and also how to find out if ASP.NET Ajax is loaded in the javascript file itself. Let's face it, you may not want your control to rely on ASP.NET Ajax, but you may want to consider reaping the benefits of it if it is loaded.

 

First thing to do is make sure you have the right references in your assembly. In this case, we will want to reference System.Web and System.Web.Extensions. Once this is done, create a javascript file inside of your assembly. Once created, click on it and go to the properties window and make sure the Build Action is set to "Embedded Resource".


Next, you will want to add an assembly attribute below the using statements to tell the assembly that it has this resource.


Now all we need to worry about is registering the script. To do this I usually override the OnLoad of the control. What we want to do here is use the ScriptManager class to see if the page has a ScriptManager control on it. If it does, we will register the script through the script manager. If it doesn't, then we want to register the script as a script include to the page.


So now we have the script registered to the page. All we need to do now is figure out if the ASP.NET Ajax framework is loaded inside the javascript. That is actually one of the easiest things to do. I just figured I would do it like M$ does, so in your javascript file do something like this:


That is all there is to it! Super easy, no?


One last point to add here. If you have done any extended work with the ScriptManager control, you will notice the ScriptMode property. If the ScriptMode="Release" the ASP.NET Ajax framework will load compressed scripts to decrease page download times. You can do the same thing in your server control. Just embed a debug and a release script into the assembly and then test the ScriptMode property to see which one to register. Now if there isn't a ScriptManager on the page, I just usually load the release script to the page.

 

Have fun writing some crazy non-ajax dependant (but can use it if it's loaded) server controls!

 

kick it on DotNetKicks.com  


Related posts

Add comment


(Will show your Gravatar icon)  

  Country flag

[b][/b] - [i][/i] - [u][/u]- [quote][/quote]