Generate URL in HTML helper

Jan Zich picture Jan Zich · Sep 18, 2009 · Viewed 61.4k times · Source

Normally in an ASP.NET view one could use the following function to obtain a URL (not an <a>):

Url.Action("Action", "Controller");

However, I cannot find how to do it from a custom HTML helper. I have

public class MyCustomHelper
{
   public static string ExtensionMethod(this HtmlHelper helper)
   {
   }
}

The helper variable has the Action and GenerateLink methods, but they generate <a>’s. I did some digging in the ASP.NET MVC source code, but I could not find a straightforward way.

The problem is that the Url above is a member of the view class and for its instantiation it needs some contexts and route maps (which I don’t want to be dealing with and I’m not supposed to anyway). Alternatively, the instance of the HtmlHelper class has also some context which I assume is either supper of subset of the context information of the Url instance (but again I don’t want to dealing with it).

In summary, I think it is possible but since all ways I could see, involve some manipulation with some more or less internal ASP.NET stuff, I wonder whether there is a better way.

Edit: For instance, one possibility I see would be:

public class MyCustomHelper
{
    public static string ExtensionMethod(this HtmlHelper helper)
    {
        UrlHelper urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
        urlHelper.Action("Action", "Controller");
    }
}

But it does not seem right. I don't want to be dealing with instances of UrlHelper myself. There must be an easier way.

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 18, 2009

You can create url helper like this inside html helper extension method:

var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var url = urlHelper.Action("Home", "Index")