11

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

NightElfik
  • 4,328
  • 5
  • 27
  • 34
  • possible duplicate of [Generate URL in HTML helper](http://stackoverflow.com/questions/1443647/generate-url-in-html-helper) – Marijn May 30 '14 at 14:03

1 Answers1

24

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);
}
Ropstah
  • 17,538
  • 24
  • 120
  • 194
  • 1
    Interesting idea, is instantiating of new helper _fast_ operation (for example like `new List()`)? Will you recommend it as solution to my problem? Or supplying UrlHelper as an argument will be _better_? – NightElfik Apr 13 '12 at 10:13
  • 3
    Performance-wise it would be practically unnoticable. The constructor doesn't do anything special other then setting some private variables. `InitHelpers` for your view does exactly the same, namely calling the constructor. If you want to ignore the fact that an extra parameter for the UrlHelper will 'clutter' your view you could add it as a parameter. However I would ignore the performance fact and go for readability. – Ropstah Apr 13 '12 at 10:16