Server.MapPath(〜)替代

时间:2016-10-17 18:25:45

标签: javascript c# asp.net asp.net-mvc

我有一个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\...

3 个答案:

答案 0 :(得分:1)

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

您应该使用辅助方法在剃刀视图中为根生成值,并将其存储在js变量中并使用它。始终使用javascript命名空间以避免全局变量值覆盖方案

所以在你的布局文件或视图中

<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

答案 1 :(得分:0)

我相信你所寻找的是:

src="@Url.Content(string.Format("~/Content/img/bancos/{0}.png", state.element.value.toLowerCase()))"

我不知道它是否直接适用于您的代码,但我相信@ Url.Content会让您在那里。

此致

答案 2 :(得分:-1)

我发现了@Href并且它按预期工作了!

var $state = $(
    '<span><img src="@Href("~/Content/img/bancos/")' + padder.pad(state.element.value) + '.png" class="img-banco" /> &nbsp; ' + state.text + '</span>'
);