Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 719
Matt Rockwell Avatar asked Aug 16 '12 13:08

Matt Rockwell


People also ask

What is the use of ViewModel in MVC?

In ASP.NET MVC, ViewModel is a class that contains the fields which are represented in the strongly-typed view. It is used to pass data from controller to strongly-typed view.

How does ASP NET MVC application work?

In an ASP.NET MVC application, a URL corresponds to a controller action instead of a page on disk. In a traditional ASP.NET or ASP application, browser requests are mapped to pages. In an ASP.NET MVC application, in contrast, browser requests are mapped to controller actions.


2 Answers

2 ways

<img src="@Url.Content("~/Images/trash.svg")">  OR 
<img src='/images/trash.svg'>
like image 106
Nagesh Ajab Avatar answered Sep 20 '22 21:09

Nagesh Ajab


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")"
like image 24
Oded Avatar answered Sep 21 '22 21:09

Oded