Display and editor templates
Display and editor templates let you define once how a type, such as an Address or a money value, should be shown or edited, and reuse that everywhere. This lesson shows DisplayFor, EditorFor, template folders and formatting attributes.
- StartView calls DisplayFor@Html.DisplayFor(m => m.ShippingAddress)
- Step 2Template name chosen[UIHint] value if set, otherwise the type name: Address
- Step 3Folders searchedViews/<Controller>/DisplayTemplates, then Views/Shared/DisplayTemplates
- Step 4Template rendersAddress.cshtml receives the Address as its model
- EndFallbackIf none is found, a built-in default template is used
The idea in plain words
Html.DisplayFor and Html.EditorFor render a property using a template chosen by its type. If you create Views/Shared/DisplayTemplates/Address.cshtml, every DisplayFor on an Address uses it, across the whole app. Editor templates work the same way from an EditorTemplates folder and are used for forms.
Simple formatting does not even need a template: attributes such as [DisplayFormat] and [DataType] change how built-in templates show values.
Example: a display template
@* Views/Shared/DisplayTemplates/Address.cshtml *@
@model Address
<address>
@Model.Street<br />
@Model.City, @Model.PostalCode<br />
@Model.Country
</address>
@* In any view *@
@Html.DisplayFor(m => m.ShippingAddress)
@Html.DisplayFor(m => m.BillingAddress)Example: formatting attributes
DisplayFor on Price shows a currency value and EditorFor on ShipDate renders a date input.
public class OrderViewModel
{
[DisplayFormat(DataFormatString = "{0:C}")]
public decimal Price { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Ship date")]
public DateTime ShipDate { get; set; }
[UIHint("Stars")] // uses DisplayTemplates/Stars.cshtml
public int Rating { get; set; }
public Address ShippingAddress { get; set; } = new();
}Common mistakes
- Naming the template file differently from the type, so it is never picked up.
- Putting editor templates in DisplayTemplates (or the reverse).
- Forgetting ApplyFormatInEditMode = true when an edit form should use the same format.
Interview question
What is the difference between a partial view and a display template?
A partial view is rendered explicitly by name wherever you call it. A display template is chosen automatically by Html.DisplayFor based on the model type or a UIHint, so defining Address.cshtml once makes every DisplayFor of an Address use it, including inside collections. Display templates suit how a type looks; partials suit reusable chunks of a page.
Want the full details? Read the official Microsoft documentation for this topic.