Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Create a Generic Display Template View for Tabular Data | ASP.NET MVC

4.20/5 (4 votes)
24 Apr 2016CPOL2 min read 15.4K   5  
Create a generic display template view for tabular data | ASP.NET MVC

Introduction

MVC display template to show all kind of tabular data. This is a generic solution/design to display tabular data.

Background

In today’s world, we have to display lots of tabular data in our websites, especially for data driven websites. As a requirement, data can be different but the layout (UI design) must be the same across the websites. One approach is to create a separate view for each of the sections where we need to show the tabular data. In this approach, if we are making any change in the UI, we have to make the same change at every place/views. So from a maintenance prospective, this is not a good idea. The second approach is to create a generic view which can show data in the tabular format.

Using the Code

First thing, we need to create a common/generic class that can contain any object:

C#
public class GenericObjectCollection
{
    public List<GenericEntity> EntitiesMapping { get; set; }
    public List<object> Collection { get; set; }
}

You can see that property Collection can keep a collection of any object. We would use this property to keep the collection object whose tabular representation is required. Another property is EntitiesMapping. It is also a collection of object (GenericEntity).

Property Collection is a collection of objects which needs to be displayed in tabular format. But this object can have many fields/properties which may be needed to display all or few. That can be specified by using property EntityMapping. Mainly it contains the name of the properties/fields which should be displayed, its header text, format and index. Index is being used to control the sequence of the fields to be displayed.

C#
public class GenericEntity : IComparable
{
    public string NameInType { get; set; }
    public string HeaderText { get; set; }
    public string Format { get; set; }
    public Int64 Index { get; set; }
    public int CompareTo(object obj)
    {
        return this.Index.CompareTo((obj as GenericEntity).Index);
    }
}

You can see the above code. I have implemented IComparable interface. It helps us to sort the collection on the basis of Index.

The next step is to create a display template for the data type GenericObjectCollection.

  • Create a folder with the name of “DisplayTemplates” under folder “Views/Shared”.
  • Create a view under folder “DisplayTemplates” and keep its name as “GenericCollection_Tabular”. Its model class should be GenericObjectCollection (created above)

Create View

Use the below code for this view:

ASP.NET
@using GenericTabularDisplay.Models
@using System.Reflection

@model GenericObjectCollection
<table cellpadding="1" cellspacing="1" border="1">
    <thead>
        <tr style="background-color:black;color:white;font-weight:bold">
            @{
                Model.EntitiesMapping.Sort();
                
                foreach (GenericEntity genEntity in Model.EntitiesMapping)
                {
                    <td>@genEntity.HeaderText</td>
                }
            }
        </tr>
    </thead>
    @{
        foreach (object entityObject in Model.Collection)
        {
            <tr>
                @{
                    foreach (GenericEntity genEntity in Model.EntitiesMapping)
                    {
                        PropertyInfo[] pies = entityObject.GetType().GetProperties();
                        foreach (PropertyInfo pi in pies)
                        {
                            if (pi.Name == genEntity.NameInType)
                            {
                                if(pi.GetValue(entityObject) != null)
                                { 
                                    <td>@pi.GetValue(entityObject)</td>
                                }
                                else
                                {
                                    <td></td>
                                }
                            }
                        }
                    }
                }
            </tr>
        }
    }
</table> 

Now your generic display template is ready for use.

We need a model class for which tabular data needs to be displayed:

C#
public class Employee
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
}

To use this generic display template, create a controller “Employee” in your MVC project and create an action “ShowEmployees” to display the tabular data.

C#
public ActionResult ShowEmployees()
{
    List<Employee> employees = new List<Employee>();
    employees.Add(new Employee()
    {
        Name = "Jitendra Kumar",
        Email = "Jitendra.Kumar@gmail.com",
        Address = "Delhi"
    });
    employees.Add(new Employee()
    {
        Name = "Nilay Sah",
        Email = "Nilay.Sah@gmail.com",
        Address = "Patna"
    });
    employees.Add(new Employee()
    {
        Name = "Atharva Sah",
        Email = "Atharva.Sah@gmail.com",
        Address = "Hajipur"
    });
    List<GenericEntity> genericEntities = new List<GenericEntity>();
    genericEntities.Add(new GenericEntity()
    {
        HeaderText = "Name",
        NameInType = "Name",
        Index = 1
    });
    genericEntities.Add(new GenericEntity()
    {
        HeaderText = "Emaployee's Email",
        NameInType = "Email",
        Index = 2
    });

    GenericObjectCollection genericObject = new GenericObjectCollection();
    genericObject.Collection = employees.ToList<object>();
    genericObject.EntitiesMapping = genericEntities;

    return View(genericObject);
}

Here you can see that, I have created a collection of object “GenericEntity” and added the object of “GenericEntity” and specified the name of the property in the class Employee to the property NameInType and its header text. I have also specified the sequence of the column in the tabular format.

At the end, I have created the object of generic/common class “GenericObjectCollection” and assigned values of its properties Collection and EntitiesMapping.

Now create a View for this action and use the below code:

ASP.NET
@model GenericTabularDisplay.Models.GenericObjectCollection

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>ShowEmployees</title>
</head>
<body>
    <div>
        <h4>Employees Data</h4>
        
        <dl class="dl-horizontal">
            @Html.DisplayFor(model => model, "GenericCollection_Tabular")
        </dl>
    </div>
</body>
</html>

Run the application and use this URL to show the output:

http://localhost:<port_number> /Employee/ShowEmployees

Result

Thanks for your time and patience.

Happy programming! :)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)