为什么 Html.DisplayFor 不在 IF 语句中工作?

M K*_* II 0 asp.net-mvc razor

我的 MVC 视图中有这段代码:

<div style="">
    @Html.DisplayFor(modelItem => item.ContentResourceFile.FileName)
    @if (item.ContentResourceFile != null && !string.IsNullOrEmpty(item.ContentResourceFile.FileName))
    {
        Html.DisplayFor(modelItem => item.ContentResourceFile.FileName);
    }
</div>
Run Code Online (Sandbox Code Playgroud)

FileName 的第一个 DisplayFor 工作它在结果中呈现,但 IF 语句中的一个不呈现。

有人可以解释为什么吗?

Gar*_*ill 5

在第一个示例中,Html.DisplayFor(...)前缀为@which 告诉 Razor 视图引擎将结果呈现为 HTML。在第二个示例中,您调用了相同的函数,但对结果不做任何处理。(想象一下,如果你说,你会得到什么输出Math.Sqrt(4)......什么都没有)。

您可能想要的是通过切换回“HTML”上下文来强制 Razor 视图引擎呈现您的结果 - 可能是这样的:

{
    <text>@Html.DisplayFor(...)</text>
}
Run Code Online (Sandbox Code Playgroud)

<text> 是 Razor 视图引擎识别的特殊伪标签,不会出现在输出 HTML 中。