【问题标题】:How define the img src path in MVC如何在 MVC 中定义 img src 路径
【发布时间】:2015-03-20 18:11:57
【问题描述】:

我的 index.cshtml 中有一张图片

myApp/Images 文件夹内还有一个文件夹 Images

如果我访问

  • http:/localhost/myApp 或
  • http:/localhost/myApp/home/

工作正常。但是如果我使用

  • http:/localhost/myApp/home/index

页面尝试在

中查找图片
  • http:/localhost/myApp/home/Images/send.png

那么我应该如何定义我的 src。

附加说明: 除了 index.cshtml,我还有一个 js 文件,其中将悬停效果添加到图像中。并且有同样的问题,这些选项都不起作用

$('#u3430_img').hover(
        function () {                
            $(this).attr("src", "~/Images/send_hover.png");
        },
        function () {                
            $(this).attr("src", "Images/send.png");
        }
);

【问题讨论】:

    标签: html asp.net-mvc


    【解决方案1】:

    您可以使用~ 引用项目顶层中的图像。

    <img src="~/Images/send.png">
    

    旧版本的 ASP.NET MVC 需要在路径周围使用 @Url.Content(),如 here 所述

    编辑:如果您想从 Javascript 更新路径,您可以指定一个绝对路径,或者将其包装在 @Url.Content() 中。

    $('#image').attr('src', '/Images/send.jpg');
    
    $('#image').attr('src', '@Url.Content("~/Images/send.png")');
    

    【讨论】:

    • 但是在 Javascript 内部呢?我尝试通过 JQuey 更改 src 并得到 http://localhost/myApp/~/Images/send.png
    • 你能发布你的jQuery代码吗?通常,如果我在 css 文件或其他文件中指定文件,如果它是 ~/Content 或其他文件中的文件,我将使用相对路径(例如:../images/send.png)
    • 更新了 javascript 的修复程序
    • 我想我将不得不选择选项 1。因为如果脚本位于单独的 js 文件中,选项 2 似乎不起作用。无法识别 Razor 代码。
    • 我认为选项 1 更好,因为你没有将它绑定到 Razor。我对 MVC 路径解析的理解是通常只尝试 /、~/ 和 ../ 的变体,直到它起作用。
    【解决方案2】:

    在Cshtml页面中添加~不是必须的。只需添加/Images/send.png ...它会来到root并遵循层次结构。

    【讨论】:

      猜你喜欢
      • 2012-09-29
      • 2021-02-12
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2018-07-13
      • 2016-07-17
      • 2014-01-20
      • 2014-11-28
      相关资源
      最近更新 更多