A code monkey "ah ha!" moment

posted by Jeff | Wednesday, February 7, 2007, 3:49 PM | comments: 0

I've been forcing myself to focus on really diving into the meat of the ASP.NET AJAX framework, and today I had a breakthrough moment.

In the most basic sense, the framework allows you to declaratively contain normal ASP.NET stuff in a special panel container, and the post-back stuff that normally happens on a page, refreshing the whole thing, automagically just updates a little area of the page instead. Almost no new learning required. Sweet.

But the real strength comes in the ability to hook into the plumbing and do even more cool stuff. There are a ton of samples. I wanted to try something simple, to extend a TextBox control that would update a Label control's text with every single keystroke, via processing on the server. (Yes, I know this is easily done client-side in Javascript, but this was more of a proof of concept.)

At first I was a little frustrated, because the documentation isn't great. It lacks context and direction. If I can find a little bit of time I fully intend to write a tutorial on this. But with enough screwing around, I finally made it work. About 30 simple lines of Javascript, coupled with a fairly simple C# class, and off I went.

The code for use in the page is simple, and every key stroke in the text box calls the server, and the server redraws the contents of the Label:

<asp:TextBox ID="MyText" runat="server" AutoComplete="off" AutoPostBack="true" OnTextChanged="MyText_TextChanged" />
<sample:KeypressExtender ID="KeyPressExtender" runat="server" TargetControlID="MyText" MinimumCharacters="2" />
<asp:UpdatePanel ID="MyUpdate" runat="server" RenderMode="block">
<ContentTemplate>
<p><asp:Label ID="Result" runat="server" /></p>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="MyText" />
</Triggers>
</asp:UpdatePanel>

The trick is really getting in touch with Javascript events, and understanding the fairly detailed way in which Microsoft has created an object model. Then it's just a matter of tying together how the client and server get along.

Now that I really get it, I feel confident I can move forward to make neat stuff. :)


Comments

No comments yet.


Post your comment: