2

I have the following code in my view:

<div class="container">
        <div class="row">
            @foreach (var item in Model)
            {
                <div class="col-lg-3 col-md-4 col-xs-6 thumb">
                    <a class="thumbnail" href="#">
                        <div class="caption">
                            <h4>Thumbnail Headline</h4>
                            <p>@Html.DisplayFor(modelItem => item.ImageCaption)</p>
                        </div>
                        <img class="img-responsive" src="@Html.DisplayFor(modelItem => item.ImageFilePath)" alt="">
                    </a>
                </div>
            }
        </div>
    </div>

@Html.DisplayFor(modelItem => item.ImageFilePath) returns a relative image path that is stored in a database in the following format: "~/Content/userProfiles/profile01/image.JPG".

When my view is rendered, my image appears to have a broken link (it is not displayed). However, when I hard-code the path in the image source it displays as required. Stated differently, <img class="img-responsive" src="@Html.DisplayFor(modelItem => item.ImageFilePath)" alt=""> returns a broken link where <img class="img-responsive" src="~/Content/userProfiles/profile01/image.JPG" alt=""> displays the image.

Why isn't my image displayed using the html helper even though it returns a path that works when hard-coded into the view? .

Bonga
  • 97
  • 11
  • Hmmm... interesting, just out of curiousity could you try to use `@Url.Content`, something like this `` and see if that helps? – Michael Sep 15 '15 at 08:08
  • Can you check generated HTML source after you use Html.DisplayFor ? isn't it renders – K D Sep 15 '15 at 08:13
  • can you say this string stored in your database with quotes? If so that could be the issue – teo van kot Sep 15 '15 at 08:16
  • @Michael, It throws an error. @K D, the generated source is ``. @teo van kot, the path is saved without the quotes. Instead of locating the image, it displays the path. – Bonga Sep 15 '15 at 08:31
  • And what happends when you delte tilda at the begining of your path from db? `/Content/userProfiles/sisokhuz@gmail.com/ZIMG_0825.JPG` – teo van kot Sep 15 '15 at 08:34
  • @teovankot Ahh, that appears to have fixed my problem. Thanks. How do I flag or vote this as an answer? – Bonga Sep 15 '15 at 08:46

1 Answers1

1

Just delete tilda (~) from the begining of your path in db.

I mean change this:

~/Content/userProfiles/sisokhuz@gmail.com/ZIMG_0825.JPG

To This:

/Content/userProfiles/sisokhuz@gmail.com/ZIMG_0825.JPG

teo van kot
  • 12,350
  • 10
  • 38
  • 70
  • Thanks. Could you please explain to me why the tilda didn't work. Or when I should and should not use it. – Bonga Sep 15 '15 at 08:51
  • @Bonga [here](http://stackoverflow.com/q/4563235/1849444) is answer why it resolve static paths on page. But when you get path from model property `VirtualPathUtility` just don't be called. – teo van kot Sep 15 '15 at 08:54