views:

5724

answers:

8

I'm trying to write a custom helper method that will output an image tag but I need to access something like Url.Content() to get a proper URL for the current context. Is there any easy way to do something like this?

A: 

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

string fullUrl = HttpContext.Current.Request.Url.AbsoluteUri;
Dave K
A: 

Why don't you write an extension method?

JSC
+2  A: 

Something like this perhaps?

public static string MyHelper(this HtmlHelper h)
{
      string url = h.ViewContext.HttpContext.Request.Url.AbsoluteUri;
}
Tim Scott
+1  A: 

You could make your own HttpHandler. You'll implement the IHttpHandler interface and the server will pass the HttpContext and you can pump out the the image early on and cut down on the processing

kRON
+8  A: 

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.

itsmecurtis
In RC1 that should be "var url = new UrlHelper(html.ViewContext.RequestContext);"
Wilka
Indeed Wilka, +1
Ropstah
This is good answer it helped me.
zidane
+3  A: 

Use the following to mimic Url.Content in code.

VirtualPathUtility.ToAbsolute("~/url/");
Schotime
A: 

yes, use this code to add url.content into your code it's work, bro and sist

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

takeshi