Display Templates in Asp.Net MVC -Part 1

Display and editor templates are way to automatically build UI based on a data model. Essentially, it allows us a way to return mark-up required to display the data for the specified model.

This is awesome because we can create templates for commonly used data models, allowing reuse and a clean razor view. The difference between display and editor templates are:

  • Display templates are used for read-only HTML elements.
  • Editor templates are used for editable HTML elements (e.g. input fields).

It was always painful to generate HTML for each property when we have a great feature in the MVC framework (@Html.EditorForModel() and @Html.DisplayForModel() and site.css (Default) where we can modify the user interface).


 

Let’s take Blog landing page as an example:

A common section called “categories” and “Tags” are important part of blog sites and may be these two sections shows many time on different pages.

so my view and it’s html and model classes would typically look something like this.

BlogPost.cs:

public class BlogPosts
    {
        public Categories CatObj;
        public Tags TagObj;
 
        public List<Categories> lstCat;
        public List<Tags> lstTag;
 
        public BlogPosts()
        {
            GetCategories();
            GetTags();
 
        }
 
        public void GetCategories()
        {
            lstCat = new List<Categories>();
            lstCat.Add(new Categories() { catId = 1, catName = "Asp.net" });
            lstCat.Add(new Categories() { catId = 2, catName = "C#" });
        }
 
        public void GetTags()
        { 
         lstTag = new List<Tags>();
         lstTag.Add(new Tags() { tagid = 1, tagName = "C++ Programming" ,Url="http://www.google.com"});
         lstTag.Add(new Tags() { tagid = 2, tagName = "SSIS", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 3, tagName = "SSRS", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 4, tagName = "SSAS", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 5, tagName = "Amazon Services", Url = "http://www.google.com" });
         lstTag.Add(new Tags() { tagid = 6, tagName = "Azure Services", Url = "http://www.google.com" });
        }
        
    }

Categories.cs

public class Categories
    {
        public int catId { get; set; }
        public string catName { get; set; }
    }

Tag.cs

public class Tags
   {
       public int tagid { get; set; }
       public string tagName { get; set; }
       public string Url { get; set; }
   }

HomeConroller.cs

public class HomeController : Controller
   {
       // GET: Home
       public ActionResult Index()
       {
           BlogPosts bp = new BlogPosts();
           return View("Index", bp);
 
       }
    }

cshtml:

@model MVCTemplate.Models.BlogPosts
 
<aside>
    @* Author:Rakesh Mahur *@
    @* This is traditional way to bind model with html by using foreach loop *@
   <h1>Common way to bind model with html</h1>
     <h2>Categories</h2>
    <ol>
        @foreach (var CatItem in Model.lstCat)
        {
            <li>
                <a href="#">@CatItem.catName</a>
            </li>
        }
    </ol>
        <h2>Tags</h2>
        <ol>
            @foreach (var tagItem in Model.lstTag)
            {
                <li>
                    <a href="@tagItem.Url">@tagItem.tagName</a>
                </li>
            }
        </ol>
     </aside>

 

 

output:

 Url: http://localhost:<port>/home/index

d1.jpg

Output is exactly same as the the desired but there are few things need to be noted that here  foreach loop is used to fetch all items from the collection and bind with html tags.So page performance directly depends on number of items in collection.

it seems ugly with lot of codes with foreach. so it’s better our views remain very simple and clean. With display templates we can make it cleaner.

How Come ?

To make code cleaner we can pass a model or a list of models into html.displayfor() and the framework will take of the rest.

before creating the display templates,folder structure is very import part of it.if you are going to create templates which will use any where in whole application as as reusable component then a folder structure looks like below and all display templates should be created under this folder.

Views->Shared->DisplayTemplates

d2.jpg

let’s create display templates for tag and categories.

Categories.cshtml

@model MVCTemplate.Models.Categories
 
        <li>
            <a href="#">@Model.catName</a>
        </li>

Tags.cshtml

@model MVCTemplate.Models.Tags
    <li>
        <a href=@Model.Url>@Model.tagName</a>
    </li>

Now add new cshtml page  with name “ViewWithTemplate” under view/home folder:

ViewWithTemplate.cshtml

@model MVCTemplate.Models.BlogPosts
 
<h1>Categories</h1>
<ol>
    
    @Html.DisplayFor(x=>x.lstCat)
</ol>
 
<h1>Tags</h1>
<ol>
    @Html.DisplayFor(x=>x.lstTag)
</ol>

Now Add new action method in homecontroller and now modified code look like this:

public class HomeController : Controller
{
    // GET: Home
    // Call this method to see view output with foreach loops
    public ActionResult Index()
    {
        BlogPosts bb = new BlogPosts();
        return View("Index", bb);
 
    }
// Call this method to see view output with Display templates.
    public ActionResult ViewWithTemplates()
       {
           BlogPosts bb = new BlogPosts();
           List<Categories> objcat = bb.lstCat;
           return View("ViewWithTemplate", bb);
 
       }

 

Output of modified code for Display templates:

 Url: http://localhost:<port>/home/ViewWithTemplates

d1

if you noticed and compare both outputs with display templates and with foreach loops as shown below,no differences found in both output but there are lot of differences at cshtml level and you can see cstmal with display templates are more manage and cleaner to traditional way.

d3.jpg

 

Another Example of Display Templates:

assume you have to show color thumbnail along with other details in tabular format as per below and you may download complete project:

colorTemplates

Sample Project for Color Thumbnail: DisplayNameForTemplate

Summary

Display templates are  a useful HTML helper built into the MVC framwork. Using them to replace foreach loops allow sus to write clean,readable code that can easily be used across the application.

Start removing your loops today !

 

 

Advertisements

One thought on “Display Templates in Asp.Net MVC -Part 1

  1. Pingback: Display Templates in Asp.Net MVC -Part 1 | SutoCom Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s