Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use Url.Content("~\stuff\hi.jpg") in controller's code?

I need the result of an Url.Content("~\stuff\") in controller's code,

How do I get this?

like image 317
Omu Avatar asked Mar 09 '11 08:03

Omu


People also ask

How do you give a controller a URL?

If you just want to get the path to a certain action, use UrlHelper : UrlHelper u = new UrlHelper(this. ControllerContext. RequestContext); string url = u.

What is URL content in MVC?

Url.Content is used when you wish to resolve a URL for any file or resource on your site and you would pass it the relative path: @Url.Content("~/path/file.htm") Url.Action is used to resolve an action from a controller such as: @Url.Action("ActionName", "ControllerName", new { variable = value })


4 Answers

in service code (i.e. away from the controllers), you can use:

string returnUrl = VirtualPathUtility.ToAbsolute("~/stuff/");

mvc1-3 exposes the Url.Content("~/stuff/"); from the UrlHelper in System.Web.Mvc, which can be readily used in your controller code.

[edited] - to make subtle distinction in the VirtualPathUtility.ToAbsolute("~/stuff/") usage.

like image 161
jim tollan Avatar answered Oct 05 '22 22:10

jim tollan


Inside the controller action you could use the Url property:

public ActionResult Index()
{
    var url = Url.Content("~/stuff/");
    ...
}

Also notice the usage of / instead of \ when dealing with relative urls.

like image 32
Darin Dimitrov Avatar answered Oct 05 '22 23:10

Darin Dimitrov


MVC 3 exposes a Url property on the controller as a UrlHelper object

var url = Url.Content("~/stuff/");

I'm not sure if it is available in older MVC versions but if not you can create your own

var urlHelper = new UrlHelper(ControllerContext.RequestContext);
var url = urlHelper.Content("~/stuff/");
like image 28
David Glenn Avatar answered Oct 06 '22 00:10

David Glenn


To get the physical file path on disk:

Server.MapPath("~\stuff\")

Controllers also include a urlHelper, available as Url, but that may not be what you need.

What is the result that you expect?

Edit: As per your request for a FilePath, Url.Content("~\stuff\") should work? Unless you use a really old ASP.net MVC that did not have a Url property on controllers.

like image 28
Michael Stum Avatar answered Oct 05 '22 22:10

Michael Stum