Call Server Side methods With Javascript in ASP.Net… Yeah Ajax

So I’ve been looking for something to match the simplicity of the old Ajax.dll WebMethods (The ability to asychronously call a method on a class from javascript) since the project was abandoned by the owner. A lot of what I saw before involved WebServices which wasn’t horrible, but I wanted Ajax.WebMethods. Come to find out, this simplicity exists in 3.5.

So let’s say I want to click on a div and have it’s innerHTML be filled with some string. Sounds like a completely viable situation for any money making business… Anyways, I could do some kind of post back and fill it, or I could use an update panel (Uhg) or I could use a Web Service or I could just bang my head on the desk and get the same level of satisfaction. But then came 3.5 and something wonderful. Take this page:

    public partial class Test : System.Web.UI.Page
        public static String GiveMeString()
            return "hi";

See somethig weird? Yeah that’s the magic of the class file. All I need is:

  • A Static Method
  • The WebMethod Attribute
  • The ScriptMethod attribute
  • Optionally something to return, but for this example it’s not optional just like Burt Renold’s mustache

And now the page file is ready, but what about the markup? Well, that’s next, so glad you asked. First the javascript:

        function ShowString()
            var test = $get('ShowThings');

        function OnGiveMeStringComplete(result)
            var test = $get('ShowThings');
            test.innerHTML = result;

First method is the method to call. The PageMethods object will allow the use of the class method that was created. The parameter being sent in is actually the method needing to be called when the server side call is complete. With that in mind, guess what the second method is… No, not ice cream. It’s the method called when the server call is compete. As you can see, I am simply changing the innerHTML of a div.

    <form id="form1" runat="server">
        <asp:ScriptManager ID="smMain" runat="server" EnablePageMethods="true" />
        <div id="ShowThings" style="background-color:Yellow;height:20px;width:20px;"

And there you have the markup. ScriptManager is a must in this case, but that’s pretty standard when dealing with Ajax in The only other thing of note is the method call on the div’s onClick. Beyond that, it’s ready to go. And if you were to make this example yourself and click on the div, you will get a ‘hi’ string in it on the first click. Amazing.