I’m trying to create a simple image gallery. Uploading works, but I have problems with displaying those images.
In the internet I found that this is the right way to do it:
[NotMapped]
public string ImageUrl
{
get
{
var isEmpty = String.IsNullOrWhiteSpace(ImgName);
if(isEmpty)
{
return Path.Combine("~/Images", "noImageAvailable.png");
}else
{
return Path.Combine("~/Images/uploaded", ImgName);
}
}
}
and in the view
@foreach (var item in Model) {
...
@{ var imgPath = HostingEnvironment.MapPath(item.ImageUrl); }
<img src="@Url.Content(imgPath)"/>
Which produces:
<img src="C:\......\Images\uploaded\0_634927659072110613.jpg"/>
What worked for me is:
[NotMapped]
public string ImageUrl
{
get
{
var isEmpty = String.IsNullOrWhiteSpace(ImgName);
if(isEmpty)
{
return Path.Combine("../Images", "noImageAvailable.png");
}else
{
return Path.Combine("../Images/uploaded", ImgName);
}
}
}
and in the view:
@foreach (var item in Model) {
.....
<img src="@Url.Content(item.ImageUrl)"/>
Which produces:
<img src="../Images/uploaded\0_634927649098750170.jpg"/>
Remarks
There are 2 differences:
- ~/Images vs ../Images
- the lines in the view
What is interesting is that the line
<img src="C:\......\Images\uploaded\0_634927659072110613.jpg"/>
displays an image in a static standalone file, while when it’s served by the IIS it doesn’t. There is just blank space instead of an image.
My question is what is the right approach, and also why does’t the first one work?
Your code is doing exactly what you’re asking. The 1st one doesn’t work because
var imgPath = HostingEnvironment.MapPath(item.ImageUrl);returns a physical path on the server to the image URL, NOT a URL. Use the 1st block with<img src="@Url.Content(item.ImageUrl)"/>. This looks like:with your view:
then …
one folder, find folder images, then …