I have talked about client callbacks in the past, and even provided a general-purpose control for invoking code on the server-side. This time, I will provide two more examples:
First, the auto complete text box. Basically, I want something similar to the AJAX Control Toolkit’s AutoCompleteExtender, but without any references to external web services, I want to use a regular server-side event instead, this is more consistent with the way ASP.NET controls work.
Here is my intended markup:
As you can see, we can set two properties:
There’s also a server-side event, AutoComplete. This will be called whenever the number of entered characters on the text box reaches the value in MinCharacters.
Here’s a screenshot:
For customizing the suggestion list appearance, we have two properties:
The AutoCompleteTextBox control itself inherits from TextBox and adds a couple of overrides. Here is its code:
As you can see, in order to use the client callbacks functionality we need to implement ICallbackEventHandler, pretty straightforward. In its RaiseCallbackEvent we raise the AutoComplete event and store its output in the request itself (HttpContext.Items collection). Then, on GetCallbackResult, we take this value and pass it to the client, this works because the request – and hence HttpContext.Items - is the same.
The AutoComplete event’s argument is pretty straightforward, basically it exposes two properties:
One possible event handler implementation could be:
The panel where the suggestion list is to be displayed is initially hidden by using CSS’ display attribute. This panel is added to the target page in its LoadComplete event, this has to be this way, because we can’t change the page’s controls in the Init or Load events, and PreRender is not called in asynchronous requests.
The OnClientItemSelected supports two types of code:
Yes, I know, one could add lots of other fancy stuff, I leave it to you! I didn’t want to add a dependency on anything else than the ASP.NET AJAX infrastructure, that’s why I kept things simple.
On the second part I will proceed with the drop down list. Stay tuned!