Friday, 25 October 2013

Disposable HtmlHelper Extensions

If you're regularly using a block of HTML elements consisting of opening tags and closing tags, you might want to employ the using pattern used by the framework's FormExtensions:

This is pretty straightforward; you need to create a class that implements IDisposable and render the opening tags in the constructor, and the closing tags in the Dispose method.

As an example I'll implement an HtmlHelper extension that renders a multi-column table with a header row containing the column titles specified, that will be rendered like this:

The first step is to create a static class for the extension method, and the extension method itself. This should be an extension method for the HtmlHelper object, and needs to return an instance of a class that implements IDisposable:

The HtmlHelper exposes a ViewContext, which has a Writer property; this is a TextWriter, and it's this object that stores the HTML that will be sent to the HttpResponse. The writer is the object that we need to pass our HTML string to. For this example, I also need the headers to render, so I've added a params parameter to the extension method:

The implementation of the disposable helper constructor builds and writes the table header, and the dispose method writes the closing tag:

The usage of the helper in the view can be changed to this:

Or this:

And gets rendered like this:

The code for the example helper class is available as a GitGist

No comments:

Post a comment