How do I use UrlHelper from within a Razor helper?

Mike picture Mike · Dec 23, 2010 · Viewed 18.3k times · Source

I'm trying to create a Razor helper like this:

@helper Render(IEnumerable<MyItem> items) {
  <ul>
    @foreach (var item in items) {
      <li><a href="@Url.Content(item.Url)">Click</a></li>
    }
  </ul>
}

Only problem here is that System.Web.WebPages.HelperPage (the base class for Razor helpers) doesn't have a Url property (of type UrlHelper). It DOES have Html (of type HtmlHelper) but no Url.

What's the cleanest way to get at a UrlHelper inside a helper? Should I new one up inline?

Answer

takepara picture takepara · Dec 24, 2010

Syntax for ASP.Net MVC Phil Haack's Repeater syntax using Razor (MVC 3)? - Stack Overflow

@helper Render(IEnumerable<MyItem> items) {
  var url = new System.Web.Mvc.UrlHelper(Context.Request.RequestContext);
  <ul>
    @foreach (var item in items) {
      <li><a href="@url.Content(item.Url)">Click</a></li>
    }
  </ul>
}

or, If using MVC3 RC2

@helper Render(IEnumerable<MyItem> items) {
  <ul>
    @foreach (var item in items) {
      <li><a href="@Href(item.Url)">Click</a></li>
    }
  </ul>
}

Hope this help.