DD4T Custom ViewModel attributes

Customer Use case

Our customer had a requirement to send some HTTP headers with the last publication date of the page in it, in order to optimize browser caching. For this reason we needed to include the last published date from Tridion in our DD4T PageModel.


The DD4T ViewModel functionality lacks the option to include the last publish date. Fortunately, you can create your own attributes.

In this blog I will show you how easy it is to create a custom attribute to include the last publish date of a page in your models.

Before you start, ensure that the last publish date is present in the DD4T IPage object (the generic object which is returned by the page factory). Out of the box, this property is not set. To change this, add below piece of code to the Web.config of your web application.

 <add key="DD4T.IncludeLastPublishedDate" value="true"/>

Your pages will now contain a last published date property, but unfortunately you’re still unable to include it in your models because the DD4T ViewModel library has no attribute for it. In this blog you will learn how to create our own custom attribute.

Step 1: Create a class that will inherit from DD4T PageAttributeBase

public class LastPublishedDate : PageAttributeBase
  • add the return type of your custom attribute
public override Type ExpectedReturnType
                return typeof(DateTime);
  • add your business logic that will provide the ‘lastpublishedDate’

Below example is simple as we get back the published from tridion when we add ‘DD4T.IncludeLastPublishedDate’ to the Web.config:

public override IEnumerable GetPropertyValues(IPage page, Type propertyType, IViewModelFactory factory)
            return new List<DateTime>() { page.LastPublishedDate };

Step 2: Use the new attribute in your model

In your model class for the page that is used by your application add a new property LastPublishedDate (Of course the property can have any name, here LastPublishedDate was a logical choice) and tag it with the custom attribute:

    public DateTime LastPublishedDate { get; set; }

Step 3: Use it!

This page was last published on @page.LastPublishedDate.