Creating a New Html Helper Extension
Repetitive code is the bane of good programming. Any way you can solve this that leaves you with something readable and dependable is a good choice, and the HtmlHelper is, true to its name, helpful in this regard. You have already seen some of the default extensions in action so we will now move on to see how to create new HtmlHelper extensions to cut down on the code you have to write. As as example I will show you the source of one of the extensions that this site uses.
The Nav Button
At the bottom of most of the pages of this site you see a navigation button or two pointing sometimes backwards, sometimes forwards and sometimes both ways. Instead of putting actual anchor tags on each of my pages I created an HtmlHelper extension to make this easier. Here is the code for the helper that creates a link back only.
public static class HtmlHelperExtensions
{
private const string _NAV_BUTTON_BACK_HTML = "<div class=\"navButton\">"<a href=\"{0}\">"<span><<"</span> {1}"</a>"</div>";
public static string NavButtonBack(this HtmlHelper helper, string text, string link)
{
return String.Format(_NAV_BUTTON_BACK_HTML, link, text);
}
}
There is an anchor in a div, which I could write by hand each time I wanted to create this Html. Or, I could use this:
<%= Html.NavButtonBack("Back to the Index", "/OnTheHtmlHelper/") %>
This also means I could change the markup for all of my nav buttons on the site by changing the code in one place. And that is always good.
Extension Methods
New HtmlHelper methods are created by writing extension methods for the HtmlHelper class. Extension methods, a feature in C# 3.0, allow you to write methods and attach them to classes almost as if a class had implemented that method itself. If the thing you want to extend is your own code, add the method to the class itself. But if you don't own the code, like in the case of any built-in .NET Framework library class, you can extend it with an extension method.
If you are not familiar with how extension methods work, I recommend taking a look at the following:
- C# 3.0 Features: Extension Methods
A nice and very simple introduction to extension methods by Dan Wahlin.
- Extension Methods (C# Programming Guide)
An article on Msdn on extension methods.
Conclusion
It is more readable and involves less typing. Also, as you can see, it is simple to implement. There is also a helper class called TagBuilder that you can use if you don't want to mess with string formatting. But that is a discussion for another time.
So if you find yourself repeating yourself in your Html, think about whether or not building an HtmlHelper will help you out.
