How do I use UrlHelper from within a Razor helper?

2019-02-07 21:58发布

问题:

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?

回答1:

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.



回答2:

I was trying to do the same thing and found this post.

I solved my problem by using @VirtualPathUtility.ToAbsolute("~/foo/bar.jpg") instead of @Url.Content("~/foo/bar.jpg")

Since @VirtualPathUtility.ToAbsolute() is static, it's available everywhere. Plus I didn't have to add any references or anything, it worked out-of-the-box from my Razor view.

If you need to use @Url.Action or @Url.RouteUrl, you'll probably want to find a real UrlHelper ... but for @Url.Content (which is what I was trying to use too), @VirtualPathUtility.ToAbsolute() works great!



回答3:

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