gpt4 book ai didi

javascript - Server.MapPath(~) 替代方案

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:25 26 4
gpt4 key购买 nike

我有一个 asp.net MVC 应用程序,我想获取远程地址以访问某个文件。

在我的 img 标签中,我使用了 ~/

截至<img src="~/Content/img/logo.svg"/>

在这种情况下,波浪号将被解释。

但我想通过 javascript 创建标签,如下所示:

var $state = $(
'<span><img src="~/Content/img/bancos/' + state.element.value.toLowerCase() + '.png" class="img-banco" /> ' + state.text + '</span>'
);

波浪号在这种情况下不会被解释。

我可以使用什么替代方案?

我试过这个:

var $state = $(
'<span><img src="@Server.MapPath(~)/Content/img/bancos/' + state.element.value.toLowerCase() + '.png" class="img-banco" /> ' + state.text + '</span>'
);

但这将返回服务器中的应用程序文件夹,如E:\inetpub\...

最佳答案

Server.MapPath 返回物理目录的路径。您需要一个到您的应用根目录(或您的图片)的相对 URL

您应该使用辅助方法在 razor View 中生成根值,并将其存储在 js 变量中并使用它。始终使用 javascript 命名空间以避免全局变量值被覆盖的情况

所以在你的布局文件或 View 中

<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
</script>
<script src="~/Scripts/PageSpecificExternalJsFile.js"></script>

并且在您的外部 javascript(PageSpecificExternalJsFile.js) 文件中,您可以像这样阅读它。

var imageLocation= myApp.Urls.baseUrl+'Content/img/bancos/hi.jpg';
// use this imageLocation now

关于javascript - Server.MapPath(~) 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40093212/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com