How to create a custom Html Helper Extension Method in MVC and Umbraco

Posted written by Paul Seal on June 06, 2017 Umbraco

What's an Html Helper Method?

An Html Helper Method is a method which returns a string or IHtmlString, usually. If you are using MVC, you will have seen it a lot already with the likes  of @Html.TextBoxFor or @Html.LabelFor etc etc.

What you pass into the method is then used and returned back to the view. In this example I am going to show you how to create one for a Breadcrumb.

Here's an example for a breadcrumb

First of all we need to create a class somewhere.

using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Umbraco.Core.Models;
using Umbraco.Web;

namespace CodeShare.Library.Helpers.General
{
    public static class HtmlExtensions
    {
        public static IHtmlString Breadcrumb(this HtmlHelper helper, IPublishedContent thisPage)
        {
            StringBuilder breadcrumb = new StringBuilder();

            IEnumerable<IPublishedContent> ancestors = thisPage.Ancestors().Reverse();

            foreach(IPublishedContent page in ancestors)
            {
                breadcrumb.Append($"<a href=\"{page.Url}\">{page.Name}</a>");
            }

            breadcrumb.Append($"<span>{thisPage.Name}</span>");

            return MvcHtmlString.Create(breadcrumb.ToString());
        }
    }
}

Explaining the code above.

It needs to be a static class so it can be called at any time. The method needs to be static too.

The first parameter HtmlHelper helper uses the keyword this to mean be an extension of HtmlHelper.

The second parameter IPublishedContent thisPage is the content model to be passed in. If you are not using Umbraco, you might pass in a different parameter here for your page model.

It then loops through the ancestors of the page in reverse order and adds some html for an a tag for each item. And finally for thisPage it just adds it in a span.

You can use this on any view or partial view now and just pass in the object for thisPage, so if it is in a view it will be Model.Content

@Html.Breadcrumb(Model.Content)

The markup it will return will be

<a href="/">Home</a><a href="/news/">News</a><span>Article</span>

Notice the return line where it says

return MvcHtmlString.Create(breadcrumb.ToString());

This makes it return IHtmlString instead of just returning the string.

So it renders in the view as Html rather than rendering it as a string.

Conclusion

Now you can see how easy they are to create, you can use them yourself to create really useful helpers.