简体   繁体   English

Server.MapPath(〜)替代

[英]Server.MapPath(~) alternative

I have an asp.net MVC application and I want to get the remote address to access a certain file. 我有一个asp.net MVC应用程序,我想获取远程地址以访问特定文件。

In my img tags, I'm using ~/ 在我的img标签中,我正在使用~/

As of <img src="~/Content/img/logo.svg"/> <img src="~/Content/img/logo.svg"/>

In this case, the tilde will be interpreted. 在这种情况下,将解释代字号。

But I want to create the tags via javascript, like this: 但我想通过javascript创建标签,如下所示:

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

The tilde won't be interpreted in this case. 在这种情况下,不会解释波浪号。

What alternative can I use? 我可以使用什么替代方法?

I have tried this: 我已经试过了:

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

But this will return the application folder in the server, like E:\\inetpub\\... 但这将返回服务器中的应用程序文件夹,例如E:\\inetpub\\...

Server.MapPath returns the path to the physical directory. Server.MapPath返回物理目录的路径。 You need a relative url to your app root (or to your image) 您需要相对于应用程序根目录(或图像)的相对网址

You should generate the value to the root in a razor view using the helper method(s) and store that in a js variable and use that. 您应该使用辅助方法在剃刀视图中生成根的值,并将其存储在js变量中并使用。 Always use javascript namespacing to avoid global variable value overwriting scenarios 始终使用javascript名称空间来避免全局变量值覆盖的情况

So in your layout file or view 因此,在您的布局文件或视图中

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

And in your external javascript( PageSpecificExternalJsFile.js ) file, you can read it like. 在您的外部javascript( PageSpecificExternalJsFile.js )文件中,您可以像这样阅读它。

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

I believe that what you are looking for is: 我相信您正在寻找的是:

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

I don´t know if it applies directly to your code but I believe that @Url.Content will get you there. 我不知道它是否直接适用于您的代码,但我相信@ Url.Content会帮助您实现目标。

Regards, 问候,

I found out about @Href and it worked as expected! 我发现了有关@Href ,它按预期工作!

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM