Display Template



 public class User  
    public int ID { get; set; }
    public string FirstName { get; set; }
    public DateTime DateOfBirth { get; set; }

If we want to display the users in different Views, it would be better to create a standardized layout for these users wherever they need to be displayed. We can accomplish this using display templates.

A display template is simply a partial view that is model-bound to the object it wants to display, and exists in the Views/Shared/DisplayTemplates folder (though you can also put it in Views/ControllerName/DisplayTemplates). Further, the name of the view (by default) should be the name of the object you want to use it as the template for.


 @model TemplatesDemo.Models.User
<div style="padding-bottom: 10px">
    <p><strong>ID:</strong> @Html.DisplayFor(m => m.ID)</p>
    <p><strong>Name:</strong> @Html.DisplayFor(m => m.FirstName)</p>
    <p><strong>Date of Birth:</strong> @Html.DisplayFor(m => m.DateOfBirth)</p>

Now, if we want to display all the users from database and show them in different Views we can simply send the list of users to the View and and use the Display Template to show them. We can use one of two methods to do that:


DisplayFor call the display template for the type of the property selected (e.g. Html.DisplayFor(x => x.PropertyName). DisplayForModel calls the display template for the @model of the view


@model IEnumerable<TemplatesDemo.Models.User>
    ViewBag.Title = "Users";