Is there a benefit to using @Url.Content(“~”)

放肆的年华 提交于 2019-12-29 07:55:15

问题


I'm new to MVC4/razor2, and I think understand the general benefit of using @Url.Content and @Url.Action- if my routing or virtual directory changes, magic-url-strings are correctly rendered.

I'm looking at some legacy Javascript-with-razor code in a view that is peppered with '@Url.Content("~")'. This renders out as '/' - or, website root. Which.... would always be the case, no?

Or is there some situation in which this could be rendered differently?

Note: it is not ~/ - just plain ol' tilde.


I'm planning on extracting the razor calls to helper-functions, and moving main block of JavaScript into an external file (for linting and general "cleanliness"). I don't need to "fix" anything that currently happening, but I would like to understand it better.


回答1:


Url.Content maps the tilde to the application root. The application root is not the same thing as the website root.

From this article http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility(v=vs.110).aspx:

An absolute virtual path starts with the literal slash mark (/). A relative virtual path is relative to the application root directory, if it is just a tilde (~) or starts with the tilde and a double backslash (~\) or the tilde and a slash mark (~/). Making a virtual path relative makes the path independent of the application.

As of MVC4 Url.Content is not needed to convert the tilde to the applicaiton root: http://beletsky.net/2012/04/new-in-aspnet-mvc4-razor-changes.html




回答2:


There appear to be two separate questions, so I'll address them individually.

Is there a benefit to using @Url.Content()

As of Razor 2 there is almost no reason to use it.

The following are equivalent (for any application root):

<a href="@Url.Content("~")">Root</a>

and

<a href="~">Root</a>

Secondly

What is the ~ (tidle)

slash(/) vs tilde slash (~/) in style sheet path in asp.net



来源:https://stackoverflow.com/questions/25625162/is-there-a-benefit-to-using-url-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!