Phiter Fernandes Phiter Fernandes - 4 days ago 4x
ASP.NET (C#) Question

Server.MapPath(~) alternative

I have an MVC application and I want to get the remote address to access a certain file.

In my img tags, I'm using


As of
<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:

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


Server.MapPath returns the path to the physical directory. 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. Always use javascript namespacing to avoid global variable value overwriting scenarios

So in your layout file or view

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

And in your external javascript(PageSpecificExternalJsFile.js) file, you can read it like.

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