0

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?

M Kenyon II
  • 4,136
  • 4
  • 46
  • 94

2 Answers2

5

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.

Gary McGill
  • 26,400
  • 25
  • 118
  • 202
4

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.

CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • I found this: http://stackoverflow.com/questions/11310940/what-does-the-in-asp-mvc-mean-do Wouldn't the whole IF statement be wrapped in it's `@`? – M Kenyon II Nov 06 '15 at 15:43
  • 1
    No, the `@` before the `if` indicates that a code block follows. You need another `@` for `Html.DisplayFor()` to indicate that it should be output. – CodeCaster Nov 06 '15 at 15:44
  • 1
    So, the first `@` puts me in code mode, the second `@` before my `Html.DisplayFor` puts me back in 'render this' mode? Sorry if I sound juvenile, I just really want to understand this instead of just copying code from Bing. – M Kenyon II Nov 06 '15 at 15:45
  • 1
    No problem, but yes, that's it. See row 1 and 2 in the table at [C# Razor Syntax Quick Reference](http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/). – CodeCaster Nov 06 '15 at 15:46