Ajax Patterns, the C# 3.0 Way

Ajax patterns represent solutions to common problems facing the developers of Ajax applications. The patternhood of these solutions stems from the fact that they tend to come up over and over again; they're not one-offs. The book Ajax Design Patterns covers 70 such patterns. The code samples (i.e., for the code running in the browser) involve JavaScript, which is what the J in Ajax stands for.

.NET developers using Volta have several options for implementing Ajax patterns. Consider Display Morphing, a pattern that allows applications to update display elements dynamically, without postbacks and full page redraws. This entails altering the style of DOM elements. Here's a C# snippet from a Volta application that shows or hides a DOM element as the mouse enters or leaves a <div>:

div.MouseEnter += delegate
{
messageDiv.Style.Display = "block";
};
div.MouseLeave += delegate
{
messageDiv.Style.Display = "none";
};

Ignoring the anonymous delegates this implementation doesn't look that different from the JavaScript Ajax Design Patterns implementation. So far, so good. But toggling the display style between "block" and "none" is quite common in Ajax applications. Wouldn't it be nice to have Show() and Hide() methods doing just that? It would, but the HtmlElement class (which is the superclass of Div) doesn't define such methods, and with it being a class from a library you can't really go ahead and add them. Or can you?

With Volta extending the reach of .NET to cover the cloud let's implement Display Morphing in a manner that takes advantage of a language feature available in C# 3.0: extension methods. (If you're not familiar with extension methods see Wes' post on Extending the World.) Here are the Show() and Hide() methods mentioned above, defined as extension methods:

static class HtmlElementExtensions
{
public static void Show(this HtmlElement element)
{
element.Style.Display = "block";
}

    public static void Hide(this HtmlElement element)
{
element.Style.Display = "none";
}

}

Without modifying the library HtmlElement class I extended it with two methods. Now they're available to the element that I want to show or hide. (I could have also extended the Div class. However other DOM elements are likely to benefit from these extensions so it makes sense to add them further up in the class hierarchy.) With Show() and Hide() in place the above code looks as follows:

div.MouseEnter += delegate
{
messageDiv.Show();
};
div.MouseLeave += delegate
{
messageDiv.Hide();
};

This implementation of Display Morphing uses a programming style closer to C# 3.0 than to the JavaScript style from Ajax Design Patterns. What style do you use in your Volta code?