Razor And HtmlHelper Extensions

HTML helpers can be fantastically useful when working on an ASP .Net MVC project, and they're dead simple. They boil down to methods which are used to encapsulate functionality to help reduce the amount of logic we end up with in a view.

For example there are helpers available to create labels and form fields, taking a property as input, and generating the relevant HTML for it.

Writing your own HTML helpers is easy and achieved by writing an extension method for the HtmlHelper class. I often hit a stumbling block when writing an extension which manifests itself in the following way:

Compiler Error Message: CS1061: 'System.Web.Mvc.HtmlHelper' does not contain a definition for 'TestMethod' and no extension method 'TestMethod' accepting a first argument of type 'String' could be found (are you missing a using directive or an assembly reference?)

An Example Extension Method

To demonstrate how to fix this, we need a quick example of an HTML helper extension method:
namespace MVC3Test.Helpers
{
public static class HtmlExtensions
{
public static MvcHtmlString TestMethod(this HtmlHelper htmlHelper, string input)
{
return MvcHtmlString.Create(input.Trim());
}
}
}

Make it work

The problem is caused by the fact that we don't have a reference to the namespace where the extension method lives. We have two options for fixing this:

Add a using directive to the view

The first thing we could do is just add a @using directive to the top of the view specifying our helper namespace:
@using MVC3Test.Helpers

Update View Folder Web.config

Adding using directives to each view that uses our helpers will quickly become tiresome. An easier way to apply this throughout the project is to update the web.config to reference the namespace.

This can happen at either the view folder level, or application folder. Either way, you need to update the web.config to add a new namespace entry, which should look something like this:


...

...

Summary

Html Helpers are a great way to reduce the complexity of your views and reuse code that is often repeated.

Just remember that when writing your own, it must be referenced from either the view, or web.config!