Templated Helpers in ASP.NET MVC

Templated Helpers in ASP.NET MVC Application

In this article, I am going to discuss the Templated Helpers in ASP.NET MVC application with examples. Please read our previous article before proceeding to this article where we discussed how to generate Password Field and Hidden Field in MVC application using the HTML Helper method.

As an ASP.NET MVC developer, we generally used to use the HTML Helper methods such as LabelFor() and TextBoxFor() to display the model properties on a view. This approach works fine in many situations, but it proves to be inadequate when we want to customize the data i.e. how the data should be presented to the end-user for the purpose of displaying and editing. If this is your requirement then you need to use the display template and editor template helpers. At the end of this article, you will understand the following pointers.

  1. Why do we need Templated Helpers in ASP.NET MVC?
  2. Types of Templated Helpers in ASP.NET MVC
  3. Types of Display and Editor Templated Helpers in ASP.NET MVC.
  4. Examples to understand Display and Editor Templated Helpers
Why do we need Templated Helpers in ASP.NET MVC?

When we use an HTML helper method, such as LabelFor() or TextBoxFor(), then it displays the model property in a fixed manner. For example, the LabelFor() extension method renders the model property name within a <label> tag. Similarly, the TextBoxFor() HTML Helper method renders a textbox in which the model property value is shown for editing.

But in some scenarios, we want more control over the data which is going to be present to the end-user either for displaying or editing purposes. For example, we have a model property that stores the currency value. Our requirement is that when displaying this currency property value to the end-user, along with the currency value we also want to show the currency symbol such as $. If this is your requirement then it is not possible with the HTML Helper methods such as LabelFor() extension method. Similarly, if you have a DateTime property and you want to display the DateTime in a specific format then you can’t do this customization using the HTML Helper methods.

To overcome the above problem means to customize the model data, the ASP.NET MVC Framework comes with templated helpers that can be used in such scenarios.

Types of Templated Helpers in ASP.NET MVC

The Templated helpers are introduced as part of MVC 2. The built-in template helpers in ASP.NET MVC are classified into 2 types are as follows.

  1. Display Templates
  2. Editor Templates 

If you want then you can also create your own custom templated helpers which we will discuss in our next article.

Types of Display Templated Helpers in ASP.NET MVC

There are three types of Display Templated Helpers available in ASP.NET MVC. They are as follows.

  1. @Html.Display(“EmployeeData”) – Used with a view that is not strongly typed. For example, if we have data stored in a ViewData or ViewBag, then we can use this templated helper using the key that was used to store data in ViewData or ViewBag.
  2. @Html.DisplayFor(model => model) – Used with strongly typed views. If our model has properties that return complex objects, then this templated helper is very useful.
  3. @Html.DisplayForModel() – Used with strongly typed views. It will work through each property of the model to display the object.
Types of Edit Templated Helpers in ASP.NET MVC

There are also 3 Edit Templated Helpers available in ASP.NET MVC. They are as follows

  1. @Html.Editor(“EmployeeData”)
  2. @Html.EditorFor(model => model)
  3. @Html.EditorForModel()

When we are going to create views, we can use the DisplayFor(), DisplayForModel(), EditorFor(), and EditorForModel() helpers even if we don’t intend to have a customized user interface. Later, if we decide to have a customized interface, all you need to do is define the display and editor templates that we will discuss in a later article.

Understanding Templated Helpers in ASP.NET MVC Application:

Let us understand the Templated Helpers in ASP.NET MVC Application with an example. First, create an empty ASP.NET MVC application with the name TemplateHelpersMVC. Then add a class with the name Employee within the Models folder as shown below.

namespace TemplateHelpersMVC.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string EmailAddress { get; set; }
        public int? Salary { get; set; }
        public string PersonalWebSite { get; set; }
        public string FullName { get; set; }
        public DateTime? HireDate { get; set; }
        public string Gender { get; set; }
    }
}
Creating Controller:

Next, add a controller with the name as EmployeeController within the Controller and then copy and paste the below codes in it.

namespace TemplateHelpersMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Details()
        {
            //Here we are hardcoded the Employee Details
            //In Realtime you will get the data from any data source
            Employee employee = new Employee()
            {
                Id = 1,
                FullName = "Pranaya Rout",
                Gender = "Male",
                HireDate = Convert.ToDateTime("2017-01-02 17:53:46.833"),
                EmailAddress = "info@dotnettutorials.com",
                Salary = 500000,
                PersonalWebSite = "https://dotnettutorials.net/"
            };
            ViewData["EmployeeData"] = employee;
            return View();
        }
    }
}

Notice that in the above code, we have added one action method with the name Details and then we stored the employee object in the ViewData using the “EmployeeData” key.

Creating the Details view:

Create the Details view and then copy and paste the below code in it.

@{
    ViewBag.Title = "Details";
}
<fieldset>
    <legend>Employee Details</legend>
    @Html.Display("EmployeeData")
</fieldset>

As you can see in the above code, we are using @Html.Display(“EmployeeData”) templated helper method to render the data. At the moment “Details.cshtml” view does not have a Model associated with it. So it is not a strongly-typed view. Now run the application and navigate to the following URL

http://localhost:61629/Employee/Details

It will display the following output as expected.

Display Templated Helpers in ASP.NET MVC Application

Now, change the implementation of the “Details” action method within the Employee controller as shown below.

namespace TemplateHelpersMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Details()
        {
            //Here we are hardcoded the Employee Details
            //In Realtime you will get the data from any data source
            Employee employee = new Employee()
            {
                Id = 1,
                FullName = "Pranaya Rout",
                Gender = "Male",
                HireDate = Convert.ToDateTime("2017-01-02 17:53:46.833"),
                EmailAddress = "info@dotnettutorials.com",
                Salary = 500000,
                PersonalWebSite = "https://dotnettutorials.net/"
            };
            return View(employee);
        }
    }
}

You can see in the above code that, instead of storing the “Employee” object in the ViewData, we are passing it to the View.

Now change the Details.cshtml view as below.
@model TemplateHelpersMVC.Models.Employee
@{
    ViewBag.Title = "Details";
}
<fieldset>
    <legend>Employee Details</legend>
    @Html.DisplayFor(model => model)
</fieldset>

In the above Details view, we have specified “Employee” as the model object. That means, here we are working with a strongly typed view, and hence we are using @Html.DisplayFor (model => model) templated helper method.

Since none of the properties of the Employee class return a complex object, the ideal choice here would be, to use @Html.DisplayForModel() templated helper as shown below.

@model TemplateHelpersMVC.Models.Employee
@{
    ViewBag.Title = "Details";
}
<fieldset>
    <legend>Employee Details</legend>
    @Html.DisplayForModel()
</fieldset>

Whether we use DisplayFor() or DisplayForModel() templates helper, in both cases, the output will be the same. So Run the application and see everything is working as expected.

Editor Templated Helpers in ASP.NET MVC:

The way we work with Display Template Helpers, in the same way, we work with Editor Template Helper in ASP.NET MVC. So let’s understand this concept by adding the Edit Action method within the Employee Controller as shown below.

namespace TemplateHelpersMVC.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Edit()
        {
            //Here we are hardcoded the Employee Details
            //In Realtime you will get the data from any data source
            Employee employee = new Employee()
            {
                Id = 1,
                FullName = "Pranaya Rout",
                Gender = "Male",
                HireDate = Convert.ToDateTime("2017-01-02 17:53:46.833"),
                EmailAddress = "info@dotnettutorials.com",
                Salary = 500000,
                PersonalWebSite = "https://dotnettutorials.net/"
            };
            return View(employee);
        }
    }
}
Now we need to add the Edit.cshtml view as shown below
@model TemplateHelpersMVC.Models.Employee
@{
    ViewBag.Title = "Edit";
}
<h2>Edit</h2>
@using (@Html.BeginForm())
{
    @Html.EditorForModel()
}

Run the application and navigates to the below URL and see everything is working as expected.
http://localhost:61629/Employee/Edit
it will display the following:

Editor Templated Helpers in ASP.NET MVC Application

Here I just show you how to use EditorForModel, the rest two approaches you can test by yourself.

In our next article, I am going to discuss how to Customizing Template Helpers in MVC application. Here, in this article, I try to explain Built-in Templated Helpers in MVC application with examples. I hope this article will help you with your needs. I would like to have your feedback. Please post your feedback, question, or comments about this article.