Ajax Control Library: Autocomplete Control to Scriptcontrol

[Part One] [Part Two] [Part Three] [Part Four] [Part Five]

Ok so in part four I showed you how to create a webcontrol from the AutoComplete control, so now it’s time to take the first four lessons and combine them. Now it’s time to have an autocomplete script control. The first part is really simple, just like before you have to:

  • Inherit from ScriptControl
  • Override the GetScriptDescriptors and GetScriptReferences methods
  • Create the .js file
  • Make the .js file an embedded resource
  • Update the assemblyinfo file in the Properties folder
  • Add the minimal needed javascript

So it will look something like this:

public class AutocompleteScriptControl : ScriptControl, INamingContainer
{
  private AutoCompleteExtender autoComplete;
  private TextBox textboxTarget;

  protected override void CreateChildControls()
  {
    base.CreateChildControls();

    autoComplete = new AutoCompleteExtender();
    autoComplete.ID = "autoCompleteMain";

    textboxTarget = new TextBox();
    textboxTarget.ID = "textboxTarget";

    Controls.Add(textboxTarget);
    Controls.Add(autoComplete);
  }

  protected override void OnPreRender(EventArgs e)
  {
    base.OnPreRender(e);
    autoComplete.TargetControlID = textboxTarget.ID;
  }

  protected override IEnumerable<ScriptDescriptor> GetScriptDescriptors()
  {
    ScriptControlDescriptor desc =
      new ScriptControlDescriptor("Test.Examples.Client.AutocompleteScriptControl", ClientID);
    desc.AddProperty("textboxTargetID", textboxTarget.ClientID);
    desc.AddProperty("autocompleteID", autoComplete.ClientID);

    return new ScriptDescriptor[] { desc };
  }

  protected override IEnumerable<ScriptDescriptor> GetScriptReferences()
  {
    return new [] { new ScriptReference
      ("Test.Examples.AutoCompleteExample.AutocompleteScriptControl.js", "Test.Examples") };
  }

}

And the script file:

if (Type)
{
    Type.registerNamespace("Test.Examples.Client");
}

Test.Examples.Client.AutocompleteScriptControl = function(element)
{
    Test.Examples.Client.AutocompleteScriptControl.initializeBase(this, [element]);

    this._autocompleteID = "";
    this._textboxTargetID = "";

    this._autoComplete = null;
    this._textboxTarget = null;
}

Test.Examples.Client.AutocompleteScriptControl.prototype =
{
    get_autocompleteID: function()
    {
        return this._autocompleteID;
    },

    set_autocompleteID: function(value)
    {
        this._autocompleteID = value;
    },

    get_textboxTargetID: function()
    {
        return this._textboxTargetID;
    },

    set_textboxTargetID: function(value)
    {
        this._textboxTargetID = value;
    },

    initialize: function()
    {
        this._autoComplete = $get(this._autocompleteID);
        this._textboxTarget = $get(this._textboxTargetID);

        Test.Examples.Client.AutocompleteScriptControl.callBaseMethod(this, 'initialize');
    },

    dispose: function()
    {
        Test.Examples.Client.AutocompleteScriptControl.callBaseMethod(this, 'dispose');
    }
}

/***********************************/

Test.Examples.Client.AutocompleteScriptControl.registerClass
    ('Test.Examples.Client.AutocompleteScriptControl', Sys.UI.Control);

And now this is the bare minimum needed to get this done.

Make an Autocomplete Control a Webcontrol

[Part One] [Part Two] [Part Three] [Part Four] [Part Five]

So in the last post I showed the easy way to use the Toolkit Autocomplete control, but it might have left you with some questions like: Do I have to keep adding a textbox everytime I want an autocomplete control? Is there an easy way to make a composite control? Is this guy an idiot?

The easy answer is: yes.

Now I’m not a huge fan of making web project controls (.ascx) unless there is heavy style formatting. For the most part if its going to be usable somewhere else and it is fairly simple to represent codewise, I’ll put it in a class library as a WebControl or ScriptControl. So how is this done with the autocomplete?

For my examples, I’ll be using the same root namespace as the Script Control examples, namely Test.Examples.AutoCompleteExample. Now that I have a wonderful folder created I’m going to go ahead and create a WebControl Class named AutoCompleteControl.

Now when I create this new control there are some things I will need:
-Has to inherit from at least WebControl (ScriptControl example I will do later)
-Has to have a textbox (The autocomplete needs a target control)
-I would strongly suggest a certain amount of properties to be exposed, basically reflecting the properties on the autocomplete
-I added the implementing of ITextControl mainly to relfect a .Text property but that isn’t really needed. I just found this useful if you end up treating this control like a textbox for say validation purposes.

    public class AutoCompleteControl : WebControl, INamingContainer
    {
        private AutoCompleteExtender autoComplete;
        private TextBox textboxTarget;

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            autoComplete = new AutoCompleteExtender();
            autoComplete.ID = "autoCompleteMain";

            textboxTarget = new TextBox();
            textboxTarget.ID = "textboxTarget";

            Controls.Add(textboxTarget);
            Controls.Add(autoComplete);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            autoComplete.TargetControlID = textboxTarget.ID;

            autoComplete.CompletionInterval = 5000;
            autoComplete.EnableCaching = EnableCaching;
            autoComplete.CompletionSetCount = CompletionSetCount;
            autoComplete.MinimumPrefixLength = MinimumPrefixLength;
            autoComplete.OnClientItemSelected = OnClientItemSelected;
            autoComplete.ServiceMethod = ServiceMethod;
            autoComplete.ServicePath = ServicePath;
        }

        public Int32 CompletionSetCount { get; set; }

        public Boolean EnableCaching { get; set; }

        public Int32 MinimumPrefixLength { get; set; }

        public String OnClientItemSelected { get; set; }

        public String ServiceMethod { get; set; }

        public String ServicePath { get; set; }

        public String Text
        {
            get
            {
                EnsureChildControls();
                return textboxTarget.Text;
            }
            set
            {
                EnsureChildControls();
                textboxTarget.Text = value;
            }
        }
    }

Well hell that was easy, wasn’t it? All I had to do is create the class, add the textbox and autocomplete as controls, and set a few properties. Voila, we now have a working autocomplete control. Now if you had read the last post on this (Page 3) then you might have noticed this new property:

CompletionInterval

What is that? Well apparently it deals with the amount of time a particular item is highlighted when hovering over it. Found this out the other day. SURPRISE!!

Couple of points from this:

Why?
– Well if nothing else, you now have a compostite control to use. The markup will supply the service location and the method to use, everything else is taken care of with this control.

– On top of that, this can now be snug in a class library (assembly) for reuse thus removing it’s need to be recopied everytime you need it in another web project.

– You can now inherit from this control to add fucntionality if you need.

– You can now convert this to a script control in order to access javascript events and other fun things.

So as you can see, this is a pretty good way to go.

Something else of note is the CreateChildControls/EnsureChildControls situation. CreateChildControls is a overridable method that is used to make sure that the controls themselves are created and handled. The nice thing about this is that you won’t run into the timing issues you might if you try to initialize controls in other methods like OnInit. Also, it allows you the use of the EnsureChildControls method. When this method is called, the CreateChildControls method is either called or not depending if it’s already been run. EnsureChildControls basically asks if CreateChildControls has been run. If it has then it doesn’t call it again, if it hasn’t then the method is called to create the controls. So as you can see, this makes it easy to guarantee that the controls have been created in order to access them. This becomes important with properties that are tied to controls as there is no guarantee that when a property is accessed the controls aren’t null. Kind of nice, huh?

Also you might have noticed that I set all the control properties that were “attached” to the autocomplete in prerender. Usually for safety, I don’t both setting any outward facing properties like that until prerender so that I know I have the latest and greatest values.

Just incase you needed the markup example:

<%@ Register Assembly="Test.Examples"
  Namespace="Test.Examples.AutoCompleteExample" TagPrefix="test" %>

<test:AutoCompleteControl ID="autoCompleteTest" runat="server"
  ServicePath="~/Service/AutocompleteWebControl.svc" ServiceMethod="GetUserNameList"
  CompletionSetCount="10" MinimumPrefixLength="1" />

HOLY SMOKES NO NEED FOR TEXTBOXES!!11

  using System.Web.UI;
  using System.Web.UI.WebControls;
  using AjaxControlToolkit;

Ajax Control Toolkit Autocomplete – How to use… simple example.

[Part One] [Part Two] [Part Three] [Part Four] [Part Five]

So in my journey to create an autocomplete control, I had it working except something really screwy with the stylesheet and how to make it look… oh I don’t know… not hideous. So on a whim I decided to give the Ajax Control Toolkit Autocomplete a try. I figured that if so many other people use it, why shouldn’t I? Or when properly translated: I hate dealing with style sheet issues and someone already had a control that works in both Firefox and IE.

Introduction… Skip if you know what this is already and just want the stupid code.

So where to begin? Well the autocomplete control itself is free and comes along with the Toolkit assembly.

Sounds good so far, so what does it do? It’s a “control”, for lack of a better word… more on that later, that can be used to attach to a textbox and allow a user to type in parts of a word and get back dropdown list like item… list.

Pretty good huh? What’s the catch? Well basically you need to use a web service to work with it, meaning either old school (.asmx?) or new school Communication Foundation services. For this example I will actually be doing it the “hard” way and use WCF. I’ve done it with both, but I figure I might as make it the more difficult of the two for fun. If I remember, the old web services are really easy to do this with. Another catch is that the web service has to be on the same server as the project.

So what isn’t it? End of world hunger, world peace, or the meaning of life. Sorry, I can only give you one of those and the autocomplete doesn’t cover that subject.

End Introduction and Begin the stupid code

Ok so you want to use the autocomplete control, huh? Well, you’ve come to the right place.

For this example, I’ll be doing the most simple version of adding the autocomplete control. This basically means setting up the service and creating some markup. Really easy. Next post I will get into how to create a web control class in a non web assembly.

Right off the bat you’ll need the toolkit assembly and create a project reference to it. Next you have to set up the WCF Service which is actually a lot easier than it sounds? Why? Because Microsoft was nice enough to create a default one for us. I’ve created a folder named Service (Brilliant!) and then I right clicked and chose Add New Item -> Ajax-Enabled WCF Service (I called it AutocompleteWebControl)… and boom already almost there.

You should now have a AutocompleteWebControl.svc.cs file in the folder and if you look at the code you get this:

namespace Test.Frontend.Service
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode =
      AspNetCompatibilityRequirementsMode.Allowed)]
    public class AutocompleteWebControl
    {
        // Add [WebGet] attribute to use HTTP GET
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
    }
}

Only thing of real importance at this point is the method with the [OperationContract] attribute. If you are going to expose a method to the autocomplete it has to have this tag. Now as you can see, we’ll need a method. At this point though I have to note two things that for the method to be correct:

  • It has to take in a String and an Integer. The first is the string that the user has typed in to search on, the second (If you choose to use it) is for limiting the number of items back. (This is set by the CompletionSetCount property on the control, more on this later.)
  • The second thing is that without any changes to how the control works, you have to send back a list of strings. This could be a deal breaker if you need to send back more information. I think it’s possible to do so, but I haven’t gotten to that point yet.

Ok so let’s create a quick method. My example is using the typical Linq to Sql stuff I’ve been using but I have faith you can figure out how to get some kind of needed information whether it’s LInq to Sql, NHibernate, LLBLGEN, or Stored Procedures…

....
  [OperationContract]
  public String[] GetUserNameList(String prefixText, Int32 count)
  {
    String[] userNames;

    userNames = LinqData.DataClasses.User
        .GetUserListByLikeName(prefixText)
        .Select(currentUser => currentUser.UserName)
        .ToArray();

    return userNames;
  }
....

Now I didn’t use the passed in integer, but I didn’t need it for this situation. As you can see this method, however follows the two rules: Takes in a string and integer and returns a string array.

Now you have the servce set up, next up is the mark up and let me tell you, it’s freakishly hard.

<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit"
tagPrefix="controlkit" %>

<asp:ScriptManager ID="smMain" runat="server" />
<asp:TextBox ID="textboxTarget" runat="server" />
<ajax:AutoCompleteExtender ID="autoCompleteMain" runat="server"
  ServicePath="~/Service/AutocompleteWebControl.svc" ServiceMethod="GetUserNameList"
  CompletionSetCount="10" MinimumPrefixLength="1" TargetControlID="textboxTarget" />

So there it is. Now you have a working autocomplete. But just in case you need it, I’ll run through this stuff.

ServicePath – This is where the web service is “located” relative to the project.

ServiceMethod – This is the name of the method it will call to fill itself.

CompletionSetCount – This is the other parameter passed into the web method and used if you want to limit the count of items returned.

MinimumPrefixLength – The minimum amount of characters needed to trigger the method call.

TargetControlID – Come on, honestly? You can’t figure that one out?

At this point you’re thinking this is great and all but what if you want to make a composite control? Well that’s the next post and it’s fairly easy.