【问题标题】:Image not displayed with html helper returning a relative image path but displays when the same path is hard-coded in the viewhtml 助手返回相对图像路径时未显示图像,但在视图中硬编码相同路径时显示
【发布时间】:2015-12-11 09:27:50
【问题描述】:

我认为有以下代码:

<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 =&gt; item.ImageFilePath) 返回以以下格式存储在数据库中的相对图像路径:“~/Content/userProfiles/profile01/image.JPG”。

当我的视图被渲染时,我的图像似乎有一个断开的链接(它不显示)。但是,当我对图像源中的路径进行硬编码时,它会根据需要显示。换句话说,&lt;img class="img-responsive" src="@Html.DisplayFor(modelItem =&gt; item.ImageFilePath)" alt=""&gt; 返回一个断开的链接,&lt;img class="img-responsive" src="~/Content/userProfiles/profile01/image.JPG" alt=""&gt; 显示图像。

为什么我的图像没有使用 html 帮助程序显示,即使它返回一个在硬编码到视图中时有效的路径? .

【问题讨论】:

  • 嗯...有趣,只是出于好奇,您可以尝试使用@Url.Content,类似&lt;img class="img-responsive" src="@Url.Content(Model.ImageFilePath)" alt=""&gt;,看看是否有帮助?
  • 使用 Html.DisplayFor 后能否检查生成的 HTML 源代码?它不是在 src 中呈现
  • 你能说这个存储在你的数据库中的字符串带引号吗?如果是这样,那可能是问题
  • @Michael,它会引发错误。 @K D,生成的源是&lt;img class="img-responsive" src="~/Content/userProfiles/sisokhuz@gmail.com/ZIMG_0825.JPG" alt="" style=""&gt;。 @teo van kot,保存路径时不带引号。它不是定位图像,而是显示路径。
  • 当您在从 db 的路径开始时删除 tilda 时会发生什么? /Content/userProfiles/sisokhuz@gmail.com/ZIMG_0825.JPG

标签: c# html asp.net-mvc image


【解决方案1】:

只需从 db 路径的开头删除 tilda (~)。

我的意思是改变这个:

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

到这里:

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

【讨论】:

  • 谢谢。您能否向我解释一下为什么 tilda 不起作用。或者我应该和不应该使用它的时间。
  • @Bonga here 回答了为什么它解析页面上的静态路径。但是,当您从模型属性VirtualPathUtility 获取路径时,请不要调用。
猜你喜欢
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
相关资源
最近更新 更多