I'm trying to write a html helper extension that outputs an image tag. I need to access (within C# code) something like Razor's @Url.Content() helper to get the proper URL for the current context. How does one do this?
-
Why don't you write an extension method?JSC– JSC2008-12-09 08:54:57 +00:00Commented Dec 9, 2008 at 8:54
-
1You need to be more specific than 'from code'. It's all code. Do you mean from a controller action?liammclennan– liammclennan2009-01-11 22:43:11 +00:00Commented Jan 11, 2009 at 22:43
-
Take a look at this article http://stephenwalther.com/blog/archive/2009/02/18/asp.net-mvc-tip-47-ndash-using-resolveurl-in-an-html.aspx by Stephen Walther.mattruma– mattruma2009-02-27 21:26:24 +00:00Commented Feb 27, 2009 at 21:26
Add a comment
|
6 Answers
Use the following to mimic Url.Content in code.
VirtualPathUtility.ToAbsolute("~/url/");
2 Comments
Zasz
This is cool, Is there any scenario/edgecase where Url.Content() provides different result than this?
Ted Ballou
If your url has query string parameters, VirtualPathUtility.ToAbsolute() will throw an error, Url.Content does not.
You can create your own instance of UrlHelper by passing in the appropriate ViewContext. For example, to do this from an image helper:
public static string CustomImage(this HtmlHelper html)
{
var Url = new UrlHelper(html.ViewContext.RequestContext);
}
At this point you can call Url.Content() or any other UrlHelper method.
1 Comment
Wilka
In RC1 that should be "var url = new UrlHelper(html.ViewContext.RequestContext);"