How do I create a MVC Razor template for DisplayFor()

OK, I found it and it’s actually very simple. In my Views\Shared\DisplayTemplates folder I have Reading.cshtml containing the following:

@model System.Int32
<span id="@ViewData.ModelMetadata.PropertyName">@Model</span>

This renders the correct tag using the name of the property as the id attribute and the value of the property as the contents:

<span id="Reading">1234</span>

In the view file this can be called using the following:

@Html.DisplayFor(model => model.Reading, "Reading")

Or if the model property is decorated with UIHint(“Reading”) then the template name can be left out of the call to DisplayFor() and it will still render using the template:

@Html.DisplayFor(model => model.Reading)

This should work equally well with custom editor templates.

Leave a Comment