简体   繁体   中英

How to I properly reference an image file from a script in an asp.net mvc project?

I have an asp.net application running on a subdirectory of my website (ie www.example.com/go/) and within a .js script file I'm trying to reference an image which is in the Images directory of my project.

When I use /Images/add.png to refer to the image, I can see the image while in debug mode, but not when the application is published (when in debug mode the application just runs on logalhost:port# and not under the /go/ url path). And when I use go/Images/add.png to refer to the image, I can see the image on the published web application, but not while testing in debug mode. What is the proper way to refer to the image resource from my script so that I can see it both in production and debug mode?

Edit

For some reason relative paths are not working. I've experimented with ./Images/add.png and ../Images/add.png .

You could create a global javascript variable pointing to the image:

<script type="text/javascript">
    var imageUrl = '@Url.Content("~/images/add.png")';
</script>

and then inside your javascript file you could use this global variable to refer to the image location instead of hardcoding its value, which as you've already found out, doesn't work when you publish the application in a virtual directory.

Needless to say that this script should be included in the view before the script that actually uses this javascript variable.

If your script is not seperate from your MVC views then just use var image = @Url.Content("~/Images/add.png") in your script.

Otherwise, either use a relative path as you know where your script files are and where your images are relative to each other:

../Images/add.png

Or use MVC to get the relative path of the content and add it to an element that you read using the script:

<div id="myDiv" data-image="@Url.Content("~/Images/add.png")"></div>

var imageUrl = document.getElementById('myDiv').attributes["data-image"].value;

Example - http://jsfiddle.net/hbBKs/1/

You need to either reference the image from a relative path based on the script so it could be

../images/file.jpg

Or you need to include some .Net into the Javascript

var image = '@Url.Content("~/uploads/file.jpg")';

the '~' symbol says to start at the root of the project (Even in that is a sub folder)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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