Ajax Webmethods, Javascript, and Anonymous Types… Booyah

As witnessed in this super awesome post I showed how to use a webmethod to get server side information with client side methods. (I know, I’m pretty sweet.) And in this one I had an example of filling a drop down list with a web method and javascript, though it was more about the anonymous method used. So what do I have now? Well a little thing about why I heart anonymous types.

What’s an anonymous type? Well it’s a type that built at compile time and requires no class file to create, but you probably have already used them if you’ve used Linq:

    var anonymous = from item in list
                    select new {
                                 Name = item.Name,
                                 Address = item.Address
                                };

And now you have a whole list of a new type that is created at compile time. Anyways, you might have been wondering why you would want these beyond linq use. Well that’s what I’m here for… that and making sure I give you a low point in your day so that things can only get better.

Now in the example from before, it was basically the idea of filling a drop down list without a postback and using a WebMethod. Now I showed the javascript needed, but I didn’t show you the web method itself.
Time to start!

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static Object GetUserList()
        {
            IList <User>userList;

            userList = LinqData.DataClasses.User
                           .GetUserList("");
            return userList
                      .Select(item => new { item.UserName, item.UserID })
                      .ToList();
        }

So there you have a method that gets some users (Waring: Actual method may vary) and you are creating a list of anonymous types that have UserName and UserID.

Now you may have noticed this:

    .Select(item => new { item.UserName, item.UserID })

Now why would I want to do that? Why can’t I just send a list of users? Well there’s nothing really stopping you from doing that, after all javascript will handle whatever you throw at it. Problem is: If you send an entire user, you’re sending everything. What if the user has an image on it? (Like an avatar) Maybe the user has a collection of addresses. Point is, that’s a lot to send out when you only need the two things. (Text and value for the dropdown list) The beauty of the anonymous types is you don’t need a new class file for the smaller version of the user thus allowing you to create a specific type that is only needed for this situation.

The nice thing to take from this is that you can easily create the bare minimum and really not sacrifice much. Why is that? Well you would think that the type is created for every user or maybe every time there is at least one instance running on the server. Fact is, the type itself is created at compile time so you don’t suffer that kind of pain. Beyond that, and I said this before, Javascript is more than capable of “reading” and “knowing” what the class has so you don’t have to worry about it needing some class off in some class file to send.

Now you could argue that you should have that class file and that it’s just good practice but I’m not convinced in this case. Mostly because this is a one time situation but, and yes it sounds funny to use “situation” again, situationally this is specific only to this instance… SITUATION

I suppose someone could argue that if I use other anonymous types elsewhere that use the same properties than I should make a new class file. There’s probably some truth to this, but on the other hand is it really necessary to go that far if you aren’t certain? I don’t know. But then again I’m fascinated by popcorn so you might not want to take my opinions seriously.

Javascript Anonymous Methods and How they help Ajax WebMethod

Ok so here’s what you’re trying to do:

You have a button and when it’s pressed you want to have it fill a drop down list without a postback. So your first thoughts are, “I like Mentos” followed by, “WebMethod” since you of course read this super awesome post. Now it might look like this:

        function GetUserList()
        {
            PageMethods.GetUserList(OnGetUserListComplete);
        }

        function OnGetUserListComplete(result)
        {
            var dropdownList = $get('dropdownListID');
            for (var i = 0; i < result.length; i++)
            {
                var item;
                item = document.createElement("option");
                item.text = result[i].UserName;
                item.value = result[i].UserID;
                dropdownList.options.add(item);
            }
        }

And GetUserList would be called on click. Fine and dandy, but this sort of bad since you’re hardcoding the id of the control. Meh. You look back at the method and see that there just isn’t a way to pass in a name, and if you didn’t you would be sooooo wrong it hurts. Shame on you. Good thing I’m here. The way you’re going to do this is to use an anonymous method. You see, as it is the PageMethod call needs a method to call post completion and that’s all it takes in. (Well not completely true, it can take in parameters for the server side method, but that’s not the point.) So you have to find a way for that PageMethod to call the method after completion AND make sure it has the list name with it.

        function GetUserList(dropdownList)
        {
            PageMethods.GetUserList(function(result) {
                 OnGetUserListComplete(result, dropdownList); });
        }

        function OnGetUserListComplete(result, dropdownList)
        {
            for (var i = 0; i < result.length; i++)
            {
                var item;
                item = document.createElement("option");
                item.text = result[i].UserName;
                item.value = result[i].UserID;
                dropdownList.options.add(item);
            }
        }

Ooo pretty tricky huh?

        PageMethods.GetUserList(function(result) {
                 OnGetUserListComplete(result, dropdownList); });

See what I did there, I created an anonymous method to be called on completion and in turn it calls the original (Though modified) OnGetUserListComplete method now. And you thought javascript sucked.

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
    {
        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        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');
            PageMethods.GiveMeString(OnGiveMeStringComplete);
        }

        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;"
          onclick="ShowString()"></div>
    </form>

And there you have the markup. ScriptManager is a must in this case, but that’s pretty standard when dealing with Ajax in asp.net. 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.