asp-append-version在使用@时呈现损坏的图像

时间:2017-07-12 18:20:07

标签: c# razor asp.net-core-mvc asp-append-version

使用Visual Studio 2015更新3和ASP.Net Core 1.1项目。

我有以下使用asp-append-version的简单图像代码。

<img src="~/images/Tulips.jpg" asp-append-version="true" />

浏览器视图源按预期使用?v = version呈现。并且图片显示。

<img src="/images/Tulips.jpg?v=uTUvJWUmAhnbcvwfyJYROibIWGa2nFDTlwxNn1zOgwo" />

我现在使用C#代码@HTML.DisplayFor

创建动态图像名称
<img src="~/images/Tulips_@Html.DisplayFor(modelItem => item.ProductNAME)_picture.png" asp-append-version="true" />

但是,浏览器视图源呈现&#34; Microsoft.AspNetCore.Mvc.ViewFeatures.StringHtmlContent&#34;而不是预期的图像名称&#34; Tulips_NAME_picture.png&#34;并给出破碎的图像图标。

<img src="/images/Tulips_Microsoft.AspNetCore.Mvc.ViewFeatures.StringHtmlContent_picture.png">

我能错过什么?我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:2)

Html.DisplayFor不应该在元素内使用,而是要创建它们,你应该使用的只是@item.ProductNAME

<img src="~/images/Tulips_@item.ProductNAME_picture.png" asp-append-version="true" />

或者,为此创建一个辅助方法:

public static string GetProductImage(Product product)
{
    return $"~/images/Tulips_{product.ProductNAME}_picture.png";
}

并像这样使用它:

<img src="@SomeClass.GetProductImage(item)" asp-append-version="true" />