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:
- A text box control that displays a dynamic pick list generated from a server-side event handler;
- A drop down list that automatically fills also based on a server-side event and a trigger value.
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:
MinCharacters: for setting the minimum number of characters after which the server-side AutoComplete event will be raised;
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:
PanelCssClass: for setting the CSS class of the boundary DIV;
PanelItemCssClass: the CSS class of each item in the suggestion list.
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:
Parameter: the value entered in the text box (read-only);
Results: the suggestion strings to return.
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.
Adds a method to the text box, getSuggestions, that fires up the client callback method on the server, using ASP.NET magic;
When a value is selected from the suggestion list, it hides and sets the text box’s value; also, if the OnClientItemSelected is set, its value will be called.
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!