53

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?

3

6 Answers 6

88

Use the following to mimic Url.Content in code.

VirtualPathUtility.ToAbsolute("~/url/");
Sign up to request clarification or add additional context in comments.

2 Comments

This is cool, Is there any scenario/edgecase where Url.Content() provides different result than this?
If your url has query string parameters, VirtualPathUtility.ToAbsolute() will throw an error, Url.Content does not.
41

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

In RC1 that should be "var url = new UrlHelper(html.ViewContext.RequestContext);"
2

Something like this perhaps?

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

Comments

2

Yes you can.

From a controller you can call:

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

Comments

0

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

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

Comments

-1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.