Templated Helpers in MVC

Templated Helpers in MVC

In this article, I am going to discuss the Templated Helpers in MVC application with examples. 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.

So here in this article, we are going to discuss what these display templates and editor templates are and how we can use them in an ASP.NET MVC application. 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 HTML Helper method.

What are Display Templates and Editor Templates in 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 present to end user either for displaying or editing purpose. For example, we have a model property which 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 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 which 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.

There are 3 types of DISPLAY templated helpers in MVC

@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.

@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.

@Html.DisplayForModel() – Used with strongly typed views. It will work thru each property of the model to display the object. 

Along the same lines, there are also 3 EDIT templated helpers available in MVC 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.

Let’s understand Templated Helpers in MVC application with an example

Let’s 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 “EmployeeData” key.

Now we need to create the Details view and then we need to copy and paste the below code within the details view.
@{
    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 MVC

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() template helper, in both the 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 MVC Examples

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 ASP.NET MVC application.

SUMMARY:

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 need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

Your email address will not be published. Required fields are marked *