Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should I use @Url.Content("~/blah-blah-blah")?

Tags:

asp.net-mvc

I can't understand the benefit(s) that I can get from Url.Content() method in ASP.NET MVC. For example, you see src='@Url.Content("~/Contents/Scripts/jQuery.js")'. Why should I use it? What reasons might exist for using it? What benefits, advantages, etc. over using plain old simple references like src='/scripts/jquery.js?

Update: Based on the answers, I'd like to know if there is any other reason for using it, other than handling virtual folders? Because I haven't seen using virtual applications that much (which of course doesn't mean that it hasn't been used that much).

like image 277
Saeed Neamati Avatar asked May 06 '12 07:05

Saeed Neamati


2 Answers

Usually, your web application is published as: www.yoursite.com/. The ~ character matches the root of the site /.

However, if you publish your site withing a virtual directory www.yoursite.com/mywebapp/, the the ~ character would match "/mywebapp/". Hard-coding Urls with "/" character would cause wrong page references.

like image 96
Lotfi Avatar answered Nov 09 '22 09:11

Lotfi


Mapping virtual paths is it's only purpose. If you do not ever need to map them and are sure your app or it folders will not sit under other apps then it won't serve you any purpose.

From the docs note if you don't use ~ you get no change in the result anyways: "Remarks If the specified content path does not start with the tilde (~) character, this method returns contentPath unchanged. "

like image 42
Adam Tuliper Avatar answered Nov 09 '22 09:11

Adam Tuliper