Writing HtmlHelper extension methods

I’ve created some pretty crazy routes for my ASP.NET MVC application, requiring some overly verbose calls to the RouteLink method in my views:

<ul>
<% foreach (var p in Model.ProjectList)
{ %>
	<li><%= Html.RouteLink(
		p.ProjectName,
		"ProjectSubRoutes",
		new RouteValueDictionary(
			new { controller = "Projects",
				editorRef = p.ProjectOwner.EditorName,
				projectRef = p.ProjectRef }),
		new RouteValueDictionary())%></li>
<% } %>
</ul>

That’s what I need to do to get a link to a project’s home page. Which, given the site is all about hosting these projects, I’m going to want to do quite a lot.

The answer is to provide my own helper methods for the views. The RouteLink method is defined as an extension method to the HtmlHelper class, which means that it is easy to make your own methods to augment the set supplied by the framework. The advantage is that you can make your methods domain-aware. If I want to have a link to a project page, I can simply create an extension method that takes an instance of a project:

public static class HtmlHelperExtensions
{
	public static string GenerateProjectLink(
		this HtmlHelper helper,
		ProjectPresenter project)
	{
		return helper.RouteLink(
			project.ProjectName,
			"ProjectSubRoutes",
			new RouteValueDictionary(
				new { controller = "Projects",
					editorRef = project.ProjectOwner.EditorName,
					projectRef = project.ProjectRef }),
			new RouteValueDictionary());
	}
}

I don’t need to worry about constructing the HTML for the link by hand, I can still use the supplied helper methods under the hood, but I save my views from being polluted with wiring details, as well as being more DRY. The view now looks like this:

<ul>
<% foreach (var p in Model.ProjectList)
{ %>
	<li><%= Html.GenerateProjectLink(p) %></li>
<% } %>
</ul>

This is more readable. Before you would have had to ferret around a bit to work out what the link was for. Now the method name clearly tells you that it is generating a project link. You don’t need to mentally duplicate the work of the routing mechanism to figure out where that request is going to end up.

One Response to Writing HtmlHelper extension methods

  1. [...] to VoteWriting HtmlHelper extension methods (1/19/2009)Monday, January 19, 2009 from GiraffeI’ve created some pretty crazy routes for my ASP.NET MVC [...]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.