What is the @Html.DisplayFor syntax for?
asp.net-mvc-3, razor
Solution
`Html.DisplayFor()` will render the DisplayTemplate that matches the property's type.
If it can't find any, I suppose it invokes `.ToString()`.
If you don't know about display templates, they're partial views that can be put in a `DisplayTemplates` folder inside the view folder associated to a controller.
Example:
If you create a view named `String.cshtml` inside the `DisplayTemplates` folder of your views folder (e.g `Home`, or `Shared`) with the following code:
@model string
@if (string.IsNullOrEmpty(Model)) {
<strong>Null string</strong>
}
else {
@Model
}
Then `@Html.DisplayFor(model => model.Title)` (assuming that `Title` is a string) will use the template and display `<strong>Null string</strong>` if the string is null, or empty.
Problem
I understand that in Razor, @Html does a bunch of neat things, like generate HTML for links, inputs, etc. But I don't get the DisplayFor function... Why would I write: ``` @Html.DisplayFor(model => model.Title) ``` when I could just write: ``` @Model.Title ```