Reputation: 14306
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:
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?
Upvotes: 0
Views: 241
Reputation: 12174
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:
[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);
}
}
}
with your view:
@foreach (var item in Model) {
.....
<img src="@Url.Content(item.ImageUrl)"/>
Upvotes: 1