how to use Url.Content(“~stuffhi.jpg”) in controller’s code?

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

How do I get this?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

Method 2

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.

Method 3

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/");

Method 4

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x