In ASP.NET MVC how can I use the Razor @Url.Content() helper from C# code?

asp.netasp.net Mvc

asp.net Problem Overview


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?

asp.net Solutions


Solution 1 - asp.net

Use the following to mimic Url.Content in code.

VirtualPathUtility.ToAbsolute("~/url/");

Solution 2 - asp.net

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.

Solution 3 - asp.net

Something like this perhaps?

public static string MyHelper(this HtmlHelper h)
{
      string url = h.ViewContext.HttpContext.Request.Url.AbsoluteUri;
}

Solution 4 - asp.net

Yes you can.

From a controller you can call:

this.Url.Content("~/Somerelativepath?somethingelse=true");

Solution 5 - asp.net

Yes, use this code to add Url.Content into your code:

var img_btn_edit = VirtualPathUtility.ToAbsolute("~/Content/images/pencil.png");

Solution 6 - asp.net

You can get to the Request object and thus the URL like this:

string fullUrl = HttpContext.Current.Request.Url.AbsoluteUri;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJC GrubbsView Question on Stackoverflow
Solution 1 - asp.netSchotimeView Answer on Stackoverflow
Solution 2 - asp.netCurtis BuysView Answer on Stackoverflow
Solution 3 - asp.netTim ScottView Answer on Stackoverflow
Solution 4 - asp.netAndrew HarryView Answer on Stackoverflow
Solution 5 - asp.nettakeshiView Answer on Stackoverflow
Solution 6 - asp.netDave KView Answer on Stackoverflow