MVC中如何定义img src路径

2024-03-06

我的 index.cshtml 带有图像

里面还有一个Images文件夹myApp/Images folder

如果我访问

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

工作正常。但如果我使用

  • http://localhost/myApp/home/index

该页面尝试在中查找图像

  • http://localhost/myApp/home/图片/发送.png

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

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

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

您可以使用以下命令引用项目顶层的图像~.

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

旧版本的 ASP.NET MVC 需要在路径周围使用 @Url.Content(),如上所述here https://stackoverflow.com/questions/11988322/what-is-the-correct-way-to-reference-an-image-in-an-asp-net-mvc-4-project

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

$('#image').attr('src', '/Images/send.jpg');

$('#image').attr('src', '@Url.Content("~/Images/send.png")');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

MVC中如何定义img src路径 的相关文章