Matt Rockwell
Matt Rockwell

Reputation: 456

What is the correct way to reference an image in an asp.net mvc 4 project?

I have image references that look like this: src="../../Images/backup5.jpg". This matches the project structure. Although in the published version, these links do not work. If i change the path to src="../Images/backup5.jpg" by removing a "../" the image will display correctly. What is the correct way to reference these images so they work in both the development version and in the published version?

Follow up, how should this look when used in css as a background: attribute?

Upvotes: 12

Views: 15199

Answers (5)

Nagesh Ajab
Nagesh Ajab

Reputation: 9

2 ways

<img src="@Url.Content("~/Images/trash.svg")">  OR 
<img src='/images/trash.svg'>

Upvotes: 1

Zizzipupp
Zizzipupp

Reputation: 1361

For the benefit of those who are not working on an MVC project, they can use:

<img src="../Images/yourImage.png" height="yourHeight" width="yourWidth"/>

where Images is a new folder added to the existing project and yourImage.png can be added to that folder by doing right-hand click on the Images folder, selecting Add and then Existing item, and navigating to where the file is stored.

Upvotes: 1

Oded
Oded

Reputation: 499002

You should be using the Url.Content helper with the tilda ~ marker (which resolves to the root of the application):

src="@Url.Content("~/Images/backup5.jpg")"

Upvotes: 23

Marius
Marius

Reputation: 1073

@Url.Content("~/Images/backup5.jpg") Seems like a decent way to do it.

Upvotes: 1

Michal Klouda
Michal Klouda

Reputation: 14521

Try src="@Url.Content("~/Images/backup5.jpg")".

Upvotes: 1

Related Questions