Dmitry Efimenko
Dmitry Efimenko

Reputation: 11188

MVC3 - Group Html Helper Extensions

I would like to group my html helper so that I could write in my view something simple as this:

@Html.SubGroup.MyCustomHelper("Hellow World")

instead of:

@Html.MyCustomHelper("Hellow World")

It appears that I cannot nest static classes in HtmlExtensions class that I use for all my helpers.

Any advices?

Upvotes: 2

Views: 490

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126587

You can't do @Html.SubGroup.MyCustomHelper("...") because there's no such thing as an "extension property" and you don't control the HtmlHelper static class.

But you could do @Html.SubGroup().MyCustomHelper("...") with the extra parens as an extension method.

public static class MyHtmlHelpers
{
    public static MyHelpers SubGroup(this HtmlHelper helper)
    {
        return new MyHelpers(helper);
    }
}

public class MyHelpers
{
    public HtmlHelper Helper { get; private set; }

    public MyHelpers(HtmlHelper helper)
    {
        this.Helper = helper;
    }

    public MvcHtmlString MyCustomHelper(string someArgument)
    {
        return MvcHtmlString.Create(someArgument);
    }
}

Upvotes: 3

Related Questions