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?
You can get to the Request object and thus the URL like this:
string fullUrl = HttpContext.Current.Request.Url.AbsoluteUri;
Something like this perhaps?
public static string MyHelper(this HtmlHelper h)
{
string url = h.ViewContext.HttpContext.Request.Url.AbsoluteUri;
}
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
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.
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.
Use the following to mimic Url.Content in code.
VirtualPathUtility.ToAbsolute("~/url/");
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");