How To Create Custom MVC Extension Methods


My good friend John MacIntyre [@JohnMacIntyre] was curious about how to add additional mark-up to an MVC Helper Method. This can be achieved by using Extension methods.

There are a few namespaces or classes that you will want to keep in mind when creating new HtmlHelper Methods of your own.

For this example I will be showing how to create the following mark-up in an extension:

<a href="[action-link]"><span>[action-link text]</span></a>

To get this started I’ll make a static class called HtmlExtensions, this is where I will build my library of ASP.NET MVC Extensions. I’ll be creating an extension method called ActionLinkWithSpan which will Extend the HtmlHelper Class. Let’s take a look:

I used the TagBuilder Class to help create the html elements I wanted to output. The UrlHelper class (which in a MVC View is the Url Property) quite easily creates the link we need based on the input parameters provided.

To use this in our View to generate our link we simply import the namespace it was placed in (or add it to the pages/namespaces section in the web.config) then select it from the intellisense (or type out the Method name) using the Html Property.

<%: Html.ActionLinkWithSpan("Navigate Here", "Index", "Home", new { id="myLink", @class="link" })%>

Well John, I hope this is very helpful.

Happy Coding!