What is the equivalent to Page.ResolveUrl in ASP.NET MVC available in the Controller?
Here are a whole bunch of ways to resolve a path that uses that application root operator (~
)
UrlHelper.Content
HttpServerUtility.MapPath
WebPageExecutingBase.Href
VirtualPathUtility.ToAbsolute
Control.ResolveUrl
To call any method with inline code on an asp.net page, the method either needs to be exposed as an instance variable on the current object, or available as a static/shared method.
A typical MVC page gives us access to quite a few of these as properties via the WebViewPage
. Ever wonder when you type @ViewData
, you get magically wired up to the ViewData? That's because you have hit a property exposed by the MVC page you're on.
So to call these methods, we don't necessarily refer to the type they represent, but the instance property that exposes them.
We can call the above instance methods like this (respectively):
href="@Url.Content("~/index.html")"
href="@Server.MapPath("~/index.html")"
href="@Href("~/index.html")"
We can do this to call a shared method that doesn't need an instance:
href="@VirtualPathUtility.ToAbsolute("~/index.html")"
AFAIK, an MVC page doesn't automatically create an instance of anything from the System.Web.UI namespace, from which ResolveUrl
inherits. If, for some reason, you really wanted to use that particular method, you could just new up a control and use the methods it exposes, but I would highly recommend against it.
@Code
Dim newControl As New System.Web.UI.Control
Dim resolvedUrl = newControl.ResolveUrl("~/index.html")
End Code
href="@resolvedUrl"