Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use UrlHelper from within a Razor helper?

Tags:

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?

like image 556
Mike Avatar asked Dec 23 '10 22:12

Mike


People also ask

What is URL action?

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.

What is URL content?

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.

What is URL Helper in MVC?

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.


2 Answers

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.

like image 170
takepara Avatar answered Oct 21 '22 04:10

takepara


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!

like image 37
remi Avatar answered Oct 21 '22 03:10

remi