Search code examples
.netasp.net-mvc-3razorrazor-declarative-helpers

Why is the HtmlHelper instance null in a Razor declarative @helper method?


Using MVC 3 RTM I'm getting a strange NullReferenceException:

@helper TestHelperMethod() {
    var extra = "class=\"foo\"";
    <div @Html.Raw(extra)></div>
}

It turns out that Html (of type HtmlHelper) is null.

I've never seen this before in a regular view. I'm starting to experiment with declarative helper methods in Razor (so far they seem a little limited) and I'm quite stumped by what I'm seeing here.


Solution

  • That's a known limitation of those helpers. One possibility is to pass it as parameter:

    @helper TestHelperMethod(HtmlHelper html) {
        var extra = "class=\"foo\"";
        <[email protected](extra)></div>
    }
    

    Another possibility is to write the helper as an extension method:

    public static class HtmlExtensions
    {
        public static MvcHtmlString TestHelperMethod(this HtmlHelper)
        {
            var div = new TagBuilder("div");
            div.AddCssClass("foo");
            return MvcHtmlString.Create(div.ToString());
        }
    }
    

    and then:

    @Html.TestHelperMethod()