M Kenyon II
M Kenyon II

Reputation: 4274

Why does Html.DisplayFor work when not in an IF statement?

I have this bit of code in my MVC view:

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

The first DisplayFor of FileName works it renders out in the results, but the one in the IF statement does not render out.

Can somebody explain why?

Upvotes: 0

Views: 1733

Answers (2)

Gary McGill
Gary McGill

Reputation: 27556

In the first example, Html.DisplayFor(...) is prefixed by @ which tells the Razor view engine to render the result as HTML. In the second example, you're calling the same function, but doing nothing with the result. (Imagine what output you'd get if you said Math.Sqrt(4) instead... nothing).

What you probably wanted was to force the Razor view engine to render your result by switching back into "HTML" context - perhaps like this:

{
    <text>@Html.DisplayFor(...)</text>
}

<text> is a special pseudo-tag recognized by the Razor view engine, and doesn't appear in the output HTML.

Upvotes: 5

CodeCaster
CodeCaster

Reputation: 151730

Because you're missing an @ before the second Html.DisplayFor(). In this context, @ instructs Razor to output the result of the following expression to the output.

Upvotes: 4

Related Questions