MVC: Re-use Views of Content Items[email protected] Czech RepublicMember, Administrator, Kentico Staff admin
edited February 2017 in Back-end Development

Would you like to create HTML snippets for content items and re-use them multiple times in an MVC site? We'd love to hear if this is what you wish to read about in a blog post or to collaborate upon with us in an open-source project.

Re-using HTML could be automated by defining strongly-typed models of content types first. Then the MVC display templates could be leveraged to re-use the looks throughout the project.

The Deliver .NET SDK exposes all content in the form of a KenticoCloud.Deliver.ContentItem type.

(Full size)

(The example content types were taken from our site.)

But, strongly-typed models could look like the following.

(Full size)

This way the MVC display templates could be defined for the specific types just by creating the Blogpost.cshtml, Testimonial.cshtml, Company.cshtml and Author.cshtml files in the ~/Views/Shared/DisplayTemplates/ folder.

Then, with a proper view model, you could just type @Html.DisplayFor(m => m.Property). ASP.NET MVC is smart enough to get the right display template for each inner part of the view model and render it accordingly. You can also create alternative view files for particular controllers or call @Html.DisplayFor(m => m.Property, differentDisplayTemplate).

More details on MVC display templates could be found in a great series from Brad Wilson.

Also, the brand new tag helpers in ASP.NET Core build upon strongly-typed models.

These are the critical points to discuss:

  • Which pattern or technique do you usually choose to re-use content and its visuals?
  • When re-using content, is it required to have it slightly modified in different places?
  • If so, shall the HTML of that content be different (e.g. different CSS class attribute, or even the wording of the content itself)?

Feel free to discuss the topic here! We'd love to hear if this is what you'd use in your projects. Then, we could write an article and discuss how we can improve the Deliver .NET SDK, together with the community.


  •[email protected] Czech RepublicMember, Administrator, Kentico Staff admin
    edited April 2017

    Hello, we've prepared a series of articles on strong typing. Be sure to check out part 1 called Strong Types Explained - Code Generator!

    Also, we're working on an article about best practices in rendering markup in MVC (coming soon).

Sign In or Register to comment.