Templates

An editor/display template is used to display a common view for a particular type. An editor template is typically used for form elements and a display template is used to display anything else.

Display Templates

Let's refactor our module to create our own display template for our "Product" model:

Create a file "Views/Shared/DisplayTemplates/Product.cshtml" inside our module with the following content:

@model DemoShop.Shop.ViewModels.Home.ProductViewModel
<article class="col-md-4">
    <h2>@Format(Model.Name)</h2>
    <p>@Format(Model.Price.ToString("c"))</p>
</article>

Note: The first line specifies the type of the model our display template is expecting.

Now we'll update the home controller's index view to make use of this display template. Open the "Views/Home/Index.cshtml" file and replace the content with the following:

@model IPagedList<DemoShop.Shop.ViewModels.Home.ProductViewModel>
<div class="row">
    @foreach (var product in Model) {
        <display for="@product" template-name="Product" />
    }
</div>
<div class="pager">
    <pager model="@Model" />
</div>

Now let's navigate to https://localhost:5001/shop to preview our changes.

This is just a basic example, but you could for example add a page to your module which displays the products for a particular brand and utilize the same display template. Now you would only have to change the view in one place.

Editor Templates

There a bunch of pre-defined editor templates in KIT, let's go back to our new/edit product views and make use of some of them:

Open the "Views/Admin/NewProduct.cshtml" file and replace <input asp-for="Name" class="form-control" /> with <editor for="Name" /> and also replace <input asp-for="Price" class="form-control" /> with <editor for="Price" />.

Now do the same for the "EditProduct" view.

Now let's navigate to https://localhost:5001/admin/products/new to preview our changes.

The final refactoring is to use the “SelectList” editor template to display a drop down list to select the page size against our list of products in the admin panel. Open the “Views/Admin/Products.cshtml” file and replace the card's footer with the following:

<div class="card-footer">
    <div class="row gx-2">
        <div class="col">
            <pager model="@Model" />
        </div>
        <div class="col-auto">
            <editor name="PageSize" template-name="SelectList" default-value="10" view-data-items="@Enumerable.Range(1, 5).Select(i => new SelectListItem(Text["{0} per page", i * 10].ToHtmlString(), (i * 10).ToString()))" view-data-showdefaultoption="false" onchange="this.form.submit()" />
        </div>
    </div>
</div>

Data Lists »