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?
A URL action is a hyperlink that points to a web page, file, or other web-based resource outside of Tableau. You can use URL actions to create an email or link to additional information about your data.
A URL (Uniform Resource Locator) is a unique identifier used to locate a resource on the Internet. It is also referred to as a web address. URLs consist of multiple parts -- including a protocol and domain name -- that tell a web browser how and where to retrieve a resource.
UrlHelper(RequestContext) Initializes a new instance of the UrlHelper class using the specified request context. UrlHelper(RequestContext, RouteCollection) Initializes a new instance of the UrlHelper class using the specified request context and route collection.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With