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?
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 realUrlHelper
... but for@Url.Content
(which is what I was trying to use too),@VirtualPathUtility.ToAbsolute()
works great!Syntax for ASP.Net MVC Phil Haack's Repeater syntax using Razor (MVC 3)? - Stack Overflow
or, If using MVC3 RC2
Hope this help.