Using MVC - Display Templates Basics

JanL@kentico.com[email protected] Czech RepublicMember, Administrator, Kentico Staff admin
edited June 2017 in Back-end Development

This is a series of articles about using MVC, mainly in relation to Kentico Cloud. Let's highlight some of the MVC artifacts and patterns that are worth using!

Contents:

Basics of ASP.NET MVC Display Templates

When it comes to rendering markup, the Display templates (and Editor templates) are maybe the most versatile artifact of MVC.

They simply allow you to define HTML markup for particular CLR types and MVC uses that HTML to render every piece of the model (or a view-model):

  • No matter where in the MVC app that piece is being rendered
  • No matter whether that piece is the main model object or just a small portion of a bigger view-model object
  • With the possibility to override the default rendering by the MVC developer at any time

The greatest explanation of templates can be found in a series of articles written by one of the main authors of MVC and xUnit, by Brad Wilson.

In Kentico Cloud, templates allow you to do two fancy things:

  • Define visuals for a content type once and use it throughout the app
  • Compose new pages of smaller re-usable units - through modular content - in the Content inventory service, without the need to contact developers

Templates vs Partial Views

You may ask what the difference between the two is. It may seem unclear as both can be used to render pieces of content on various places. Also, they both use the same implementation: both are just .cshtml files with arbitrary Razor syntax inside.

It can be put in one sentence: While partial views are more visual-centric, templates are more component-centric.

In a slightly more detail: Partial views are suited for situations when visual presentation is the most important thing; no matter of the data structure below. Hence, a partial view is not always supposed to be strongly typed.

Templates, on the contrary, should always be strongly typed using the @model directive. They also should be named according to the names of types they represent. It's because MVC uses a naming convention to select them for rendering if no other rendering artifact is selected explicitly by the developer.

The nicest thing about MVC is that almost none of its conventions mean any constraints or barriers for developers. You can, therefore, mix and match views, partial views and templates. You can invoke a template from within a view or a partial view, and vice versa.

Like so:

  • View

    • Template
  • View

    • Partial view
      • Template
  • View

    • Template
      • Partial view
  • View

    • Template
      • Partial view
        • Template

To be more precise, there is also one formal difference between templates and partial views. Whereas partial views get rendered through the Html.Partial or Html.RenderPartial methods, templates get invoked through the Html.Display, Html.DisplayFor and Html.DisplayForModel helper methods.

How It Works

Templates always take the information about the model from the current ModelMetadata object. From there, they pick semantics about the data. Not only the CLR type itself, but various other hints provided mainly by attributes seeded in the source code of the model classes. These attributes come from the System.ComponentModel.DataAnnotations, System.ComponentModel and System.Web.Mvc namespaces.

The most useful attributes are:

Attribute Description
DataTypeAttribute Allows for fine-grained type definitions using well-known hints. Examples: [DataType(DataType.Html)], [DataType(DataType.Email)], [DataType(DataType.PhoneNumber)]. A template file named according to the enum's string value can be created.
DisplayFormatAttribute The ConvertEmptyStringToNull parameter can make the view code a bit cleaner. The NullDisplayText parameter then elegantly sets a string that gets rendered automatically instead of a template in case of null values.
UIHintAttribute Allows overriding the default convention in searching for templates. By default, template file named according to a type is sought for. This way, the default template can be set for a CLR type for the scope of the whole application.

Filesystem Locations

As for where the template is being sought for, it is in the following folders:

  • ~/Views/[controller name]/DisplayTemplates/
  • ~/Views/Shared/DisplayTemplates/

Should there be areas defined in the MVC app, then the area-specific locations are also being scanned beforehand.

Explicit Template Invocation

Apart from letting MVC scan for a template or overriding the default selection mechanism globally, you can always invoke a specific template explicitly:

@Html.DisplayFor(vm => vm.SomeProperty, "SpecificTemplate")

The 'SpecificTemplate' is just the name of a file without its .cshtml extension. The search locations and the order are the same as above.

There can be templates defined for all kinds of CLR types, from simple BCL types to the most complex ones. By invoking proper templates from within other templates, the code of the presentation layer may become very, very clean and maintainable. No spaghetti code anymore.

Wrapping Up

So, we've covered the basics of templates. If you haven't touched on templates yet, now you know that they are a reusable, component-centric presentation artifact that is used throughout the whole app. You know that it's a good idea to stick to some attributes to squeeze the maximum out of templates. You also know how to nest them within one another, combine them with views and how you can step out of the conventional process of selecting templates. Hopefully, this will give you a good head start to use them to the greatest effect.

Now, is there anything you missed in the article? Was anything unclear or unintelligible? Tell us in the comments below!

Let's continue in part 4 to see a few edge cases, to see how you can parameterize the behavior of the template, and how you could use templates in Kentico Cloud to get the best results.

Tagged:
Sign In or Register to comment.