Displaying shared content

This page describes how you can display reusable content, linked to pages by content editors, in your MVC application. The shared content – linked to individual pages via a field with the Pages data type and form control – is accessible through the Fields property of the page type’s generated class.

Displaying reusable content

  1. Open your MVC project in Visual Studio.

  2. Create a view model used to represent the page type and fill it with any data you require. All fields specified for a given page type are exposed by the Fields property. In the following example, an ArticleViewModel is instantiated with an Article page’s Title,Summary,TextTeaser, and all of its linked pages stored in the RelatedArticles property:

     public class ArticleViewModel
         public string Title { get; set; }
         public string Summary { get; set; }
         public string Text { get; set; }
         public DocumentAttachment Teaser { get; set; }
         // Represents a collection of shared content
         public IEnumerable<ArticleViewModel> RelatedArticles { get; set; }
         // Creates a view model instance for a given Article
         public static ArticleViewModel GetViewModel(Article article)
             return new ArticleViewModel
                 // Iterates over the collection of shared content
                 // converts items of the 'Article' type to their respective view models        
                 RelatedArticles = article.Fields.RelatedArticles.OfType<Article>().Select(GetViewModel),
                 Title = article.Fields.Title,            
                 Summary = article.Fields.Summary,
                 Text = article.Fields.Text,
                 Teaser = article.Fields.Teaser

    We recommend creating a separate view model for each page type you need to include in the collection of shared content.

  3. Pass the model to a view.

  4. Access the individual related pages stored in the model. For example:

     @model ArticleViewModel
     @if (Model.RelatedArticles.Any())
         // Iterates over each of the pages of a specific type in the same order in which they are added on the page's Content tab
         @foreach (var article in Model.RelatedArticles)
             // Displays the image stored in the model's 'Teaser' field
             <img src="@Url.Kentico().Attachment(article.Teaser) class="article-tile-image" />

    By default, the pages are accessed in the same order in which they are added by content editors on the page’s Content tab.