Search code examples
asp.net-mvc-3extension-methods

How to call UrlHelper when writing extension for HtmlHelper


I have ASP.NET MVC3 project and I am writing some extension methods that returns HTML but I need UrlHelper for rendering them. To do that I am extending UrlHelper but I don't like the semantics because UrlHelper should work with URLs and HtmlHelper with HTML. I'd like to extend HtmlHelper with this methods instead of UrlHelper.

My problem is that I don't now how to access UrlHelper from extension method of HtmlHelper, is it even possible? Or I have to stick with UrlHelper extensions.

I know that I can send Url helper as an argument but I don't like this solution very much.

Following code is sample of extension method I am talking about:

public static HtmlString AnchorLink(this UrlHelper url, string text, string action, string anchor) {
    return new HtmlString(string.Format("<a href=\"{0}#{2}\">{1}</a>", url.Action(action), text, anchor));
}

Thanks


Solution

  • You could instantiate an UrlHelper yourself...

    public static HtmlString AnchorLink(this HtmlHelper html, string text, string action, string anchor) {
        var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    }