Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (i.e. 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.

like image 476
JSideris Avatar asked Feb 25 '13 15:02

JSideris


People also ask

How do you reference an image in JavaScript?

In JavaScript, get a reference to the image tag using the querySelector() method. Then, assign an image URL to the src attribute of the image element.

What is minification and bundling of files in MVC?

Bundling and minification are two techniques you can use in ASP.NET 4.5 to improve request load time. Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)

How to create bundling in MVC?

Bundling and Minification are two performance improvement techniques that improves the request load time of the application. Most of the current major browsers limit the number of simultaneous connections per hostname to six.


1 Answers

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.

like image 64
Darin Dimitrov Avatar answered Nov 05 '22 06:11

Darin Dimitrov