【问题标题】:Mvc relative path using virtual directory..help!使用虚拟目录的 Mvc 相对路径..help!
【发布时间】:2010-05-18 04:44:24
【问题描述】:

当我将图像/脚本/css 文件拖放到视图中时,相对路径将自动用于引用文件。

示例:

<link href="../../Content/style.css" rel="stylesheet" type="text/css" />
 <script src="../../Scripts/jquery-min.js" type="text/javascript"></script>
 <img src="../../Images/logo.jpg" />

当我将它托管在我的根目录上时它工作正常,但如果我使用虚拟目录,那么只有我的 css 文件能够正确引用,其余的将返回 404...因为它将引用 http://{root}/Images/logo.jpg而不是http://{root}/{virtual directory}/Images/logo.jpg

但是为什么 css 文件可以工作?以及如何为根目录和虚拟目录情况正确指定相对路径?

【问题讨论】:

    标签: html asp.net-mvc model-view-controller relative-path


    【解决方案1】:

    类似...

       <script type="text/javascript"  
                src="<%= Url.Content ("~/Scripts/jquery.js") %>">
       </script> 
    

    会成功的

    【讨论】:

      【解决方案2】:

      此外,与Kazi Manzur's MVC Best Practices 相关,您可以创建 UrlHelper 方法来处理所有内容(脚本、样式表、图像等)文件路径的创建。这样,如果你改变目录,你所要做的就是改变相应的UrlHelper:

         public static string Style(this UrlHelper url, string fileName)
         {
             return url.Content("~/content/{0}".FormatWith(fileName));
         }
      
         public static string Script(this UrlHelper url, string fileName)
         {
             return url.Content("~/scripts/{0}".FormatWith(fileName));
         }
      

      然后,在您的 ViewPage 或 MasterPage 中,您可以像这样编写路径:

      <link  href="<%= Url.Style("site.css")%>" rel="stylesheet" type="text/css"/>
      

      【讨论】:

      • 有趣。我想这用于处理生产与开发或测试配置不匹配的情况。似乎从网络配置中读取这些内容会使其更加动态。
      • 谢谢,但是使用这种方法我会在 Visual Studio 中丢失我的 javascript intelliSense。我现在要做的是添加一个自定义的httpmodule,在页面返回给客户端之前,它将“../../”替换为html中的绝对路径。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2011-06-24
      • 2014-12-18
      • 1970-01-01
      相关资源
      最近更新 更多