简体   繁体   中英

Image not getting displayed in ASP.NET MVC

I am trying to display a logo on my web-page. But, it's not getting displayed in the browser. The image is saved in the Views/Shared folder. I've following code in Views/Shared/_Layout.cshtml :

<img src="~/Views/Shared/sabariimg1.jpg" alt="Sample pic" />

But, it's not getting displayed in the browser. Instead, following gets rendered:

You can use @Url.Content(String fileName) to pickup that image file in source folder. Like this:

<img id="img_logo" alt="Logo" src="@Url.Content("~/Content/Images/abc.png")" />

The image is saved in the Views/Shared folder.

  1. The folder Views/Shared is for view files (.cshtml) and not for shared data. You can create a new folder in your root directory like Images where you save all your images. For logo, better have this files structure Images/Logos or in Content folder like Content/Images/Logos . It's not required but a good practice !
  2. To access a file from any folder you can use the ~ that is the absolute path for the root application. This means, to access your file image you can just use the following line of code:
<img id="mylogo" src="~/Images/Logos/myimage.jpg" alt="my image logo" class="logo" />

I think this should work for any ASP.NET Web-forms or MVC web application.

You have said your image is in Shared Folder , so the url is not true !! your image should be in Images/Logos/ Folder.

I made a mistake, if that helps anyone in this old question

I had during development without thinking about it changed my code to:

<img src="../Images/filename.jpg" />

This worked for a while but some views did not load the image

I changed it back to the relative path to root and everything works fine again as it will always find the image through the root path no matter which view causes the reload of the page:

<img src="~/Images/filename.jpg" />

This was happening to me. My problem was solved by publishing the Images folder to the server (in VS19, mouse right click on the folder -> Publish)

I had faced the same issue. I have shared the 'Image' folder in the Server. Now the image is getting displayed. I am not sure how much it helps for but it's more related this problem.

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