mare
mare

Reputation: 13083

Custom HTML helper class in MVC

I've been using custom HTML helper extensions for some time now. Lately I've decided it would be nice to use helper that look like this

<%: Style.MyCustomExtensionMethod(...) %>

or

@Style.MyCustomExtensionMethod("abcd")

I searched all over the net but always ran into custom HTML helpers that are called via Html.

I also inherited from HtmlHelper class like this

public static class Style : HtmlHelper
{
    public static string test(this HtmlHelper helper, string text)
    {
        return text;
    }
}

but that didn't work (in the View it says it cannot find method test() that takes one parameter.

Upvotes: 0

Views: 1561

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

If you want to achieve such syntax in your view you could always:

public static class Style
{
    public static MvcHtmlString MyCustomExtensionMethod(string foo)
    {
        ...
    }
}

Obviously because you are not extending an HtmlHelper you no longer have access to the HttpContext which limits the usefulness of such thing.

Another possibility is to modify the base class all your razor views are deriving from by extending WebViewPage and adding a custom property to which you could write extension methods later. The question you have to ask yourself is: is it worth it?

Personally I find nothing wrong/ugly/incorrect about:

@Html.MyCustomExtensionMethod("abcd")

or:

@Url.MyCustomExtensionMethod("abcd")

Those are the de-facto standards in ASP.NET MVC and every developer should be familiar with. It's also easier with Intellisense and discoverability of your custom helpers.

Upvotes: 1

Related Questions