ASP.NET MVC 相对路径 [英] ASP.NET MVC Relative Paths
问题描述
在我的应用程序中,我经常不得不使用相对路径.例如,当我引用 JQuery 时,我通常是这样做的:
In my applications, I often have to use relative paths. For example, when I reference JQuery, I usually do so like this:
<script type="text/javascript" src="../Scripts/jquery-1.2.6.js"></script>
现在我正在过渡到 MVC,我需要考虑一个页面可能具有的不同路径,相对于根.这当然是过去 URL 重写的一个问题,但我设法通过使用一致的路径来解决它.
Now that I'm making the transition to MVC, I need to account for the different paths a page might have, relative to the root. This was of course an issue with URL rewriting in the past, but I managed to work around it by using consistent paths.
我知道标准的解决方案是使用绝对路径,例如:
I'm aware that the standard solution is to use absolute paths such as:
<script type="text/javascript" src="/Scripts/jquery-1.2.6.js"></script>
但这对我不起作用,因为在开发周期中,我必须部署到测试机器上,应用程序将在虚拟目录中运行.当根更改时,根相对路径不起作用.此外,出于维护原因,我不能简单地在部署测试期间更改所有路径 - 这本身就是一场噩梦.
but this will not work for me as during the development cycle, I have to deploy to a test machine on which the app will run in a virtual directory. Root relative paths don't work when the root changes. Also, for maintenance reasons, I cannot simply change out all the paths for the duration of deploying the test - that would be a nightmare in itself.
那么最好的解决方案是什么?
So what's the best solution?
由于这个问题仍在接收意见和答案,我认为更新它可能是谨慎的,注意从 Razor V2 开始,对根相对 url 的支持已经被支持,所以你可以使用
Since this question is still receiving views and answers, I thought it might be prudent to update it to note that as of Razor V2, support for root-relative urls is baked in, so you can use
<img src="~/Content/MyImage.jpg">
无需任何服务器端语法,视图引擎会自动将 ~/替换为当前站点根目录.
without any server-side syntax, and the view engine automatically replaces ~/ with whatever the current site root is.
推荐答案
试试这个:
<script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery-1.2.6.js")%>"></script>
或者使用 MvcContrib 并执行以下操作:
Or use MvcContrib and do this:
<%=Html.ScriptInclude("~/Content/Script/jquery.1.2.6.js")%>
这篇关于ASP.NET MVC 相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!