HTML Helpers in MVC: Part 3

This is part 3 of HTML Helpers series.

In the previous two articles of this series we discussed how to render a TextBox, dropdownlist, radio button and a checkbox control using HTML Helpers.

To learn more please refer to the link given below.

1. HTML Helpers in MVC: Part 1

2. HTML Helpers in MVC: Part 2

This article explains how to use the Display and Editor Template HTML Helpers.

Display Template Helpers

There are three Display Template Helpers.

1. @Html.Display(): This template can be used with a view that is not strongly-typed.

2. @Html.DisplayFor(): This template can be used with a strongly-typed view.

3. @Html.DisplayForModel(): This template can be used with a strongly-typed view.

Editor Template Helpers

There are three Editor Template Helpers.

1. @Html.Editor(): This template can be used with a view that is not strongly-typed.

2. @Html.EditorFor(): This template can be used with a strongly-typed view.

3. @Html.EditorForModel(): This template can be used with a strongly-typed view.

In both the templates, the last two templates can be used with strongly-typed views. But is there any difference between the two?

Yes.

@Html.DisplayFor() and @Html.EditorFor() can be used when your model returns a complex object.

Let's look at an example of each of these templates. But before that let's create an MVC application that we will use for the demo.

Step 1

Open Visual Studio and select "File" -> "New" -> "Project...".



Select MVC 4 as the project.



Click OK.

Select the project template as “Empty” and the view engine as “Razor”.



Click OK.

An empty MVC 4 application will be created. The next step is to install the Entity Framework.

Step 2

Go to Tools -> NuGet package manager -> Manage NuGet Packages for Solution.



Click on the Install button.







Select your current project.



Click I Accept.





Once it is installed, click the Close button in the Manage NuGet Packages.

For the demo we will be using this database table.



Step 3

The next step is to add two class files to the Models folder.

Create a class “Employee” and add seven auto-implemented properties.

  1. using System;  
  2. using System.ComponentModel.DataAnnotations.Schema;  
  3.   
  4. namespace DisplayAndEditTemplates.Models 
    {  
  5. [Table("tblAttibute")]  
  6. public class Employee 
       {  
  7.    public int Id { getset; }  
  8.    public string EmployeeName { getset; }  
  9.    public string Gender { getset; }  
  10.    public DateTime? HireDate { getset; }  
  11.    public string EmailAddress { getset; }  
  12.    public int Salary { getset; }  
  13.    public string PersonalBlog { getset; }  
  14.    }  
  15. }  
NOTE

The name of the properties must match the column name in the table.

We will be working with the tblAttibute table, so it is important to map our Employee class with the table or else it will create a new table in the database.

Add another class file “EmployeeDB.cs”.
  1. using System.Data.Entity;  
  2.   
  3. namespace DisplayAndEditTemplates.Models 
    {  
  4. public class EmployeeDB : DbContext
     {  
  5.    public DbSet<Employee> Employees { getset; }  
  6.  }  
  7. }  
To learn more about DbContext and DbSet, click here.

Add a connection string to the root web.config file.
  1. <connectionStrings>  
  2. <add name="EmployeeDB" connectionString="server=.; database = db_Attibutes; Integrated Securiry =SSPI" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Make sure the connection string name matches the class name “EmployeeDB”.

Step 4

The next step is to add a controller.



Click Add.

Step 5

The next step is to add a view but before that create a new object of the EmployeeDB class to the Index method.
  1. using DisplayAndEditTemplates.Models;  
  2. public ActionResult Index()
     {  
  3.    EmployeeDB empDB = new EmployeeDB();  
  4.    List<Employee> employees = empDB.Employees.ToList();  
  5.    return View(employees);  
  6. }  
Add an Index view.



Just like that, create a Details view but before that add the following to the Details action method.
  1. public ActionResult Details(int id) 
    {  
  2. EmployeeDB empDB = new EmployeeDB();  
  3. ViewData["Employee"] = empDB.Employees.Single(x => x.Id == id);  
  4. return View();  
  5. }  
What we did

We created an instance of the EmployeeDB class in the details action method.

This EmployeeDB class has a property “Employees” that returns a collection of employees back, out of which we want the details of a single employee. For that we used a Single extension method. In this method we passed a predicate x=> x.Id == id that retrieves the details of the employee whose Id matches the Id passed in as a parameter in the details action method.

After getting the employee records we stored it in a ViewData object.

Add a details view.





Now let's see how to work with the template HTML Helpers.

To render and display the details of an employee, all we need to do is to pass the ViewData key as a parameter in the Display HTML Helper.
  1. @Html.Display()  
  2. @{  
  3. ViewBag.Title = "Details";  
  4. }  
  5.   
  6. <h2>Details</h2>  
  7.   
  8. @Html.Display("Employee")  
Run the application


Click on the Details link.


Look at the output above, we got all the details of an employee.

The Display, DisplayFor and DisplayForModel always loop through each property and renders the HTML. But it generates the HTML for all the properties.

As we know in a real scenario the Id column is never displayed to the front-end user.

So, can we hide the Id column, since we are using the template to generate the required HTML for us?

Yes, by decorating the Id property in the Employee class with the HiddenInput attribute.
  1. [HiddenInput(DisplayValue=false)]  
  2. public int Id { getset; }  
NOTE

The HiddenInput attribute is present in the System.Web.Mvc namespace.

Run the application


So, now the Id column is hidden.

@Html.DisplayFor()

This DisplayFor template can be used whenever a View returns a complex type back.

Let's understand this practically.
Add a new class file to the Models folder “Manager”.
  1. using System.Linq;  
  2.   
  3. namespace DisplayAndEditTemplates.Models
     {  
  4.    public class Manager 
       {  
  5.       public Employee EmployeeManager {  get {  EmployeeDB empDB = new EmployeeDB();  
  6.       Employee SingleEmployee = empDB.Employees.Single(x => x.Id == 1);  
  7.       return SingleEmployee;           }      }  
  8.    }  
  9.  }  
In the Manager class, we add a property EmployeeManager that returns an employee object back meaning this property returns a complex type back.

In the get accessor all we did is, we created an instance of the EmployeeDB class and invoked the Single extension method on the Employees property that will provide us the only employee details with an id of 1.

Flip to the HomeController and create a new action method.

  1. public ActionResult ComplexDetails()
     {  
  2.   Manager m = new Manager();  
  3.   return View(m);  
  4. }  
Add a strongly-typed view.



Select Manager as a Model class and click Add.

In the ComplexDetails view write the following.
  1. @model DisplayAndEditTemplates.Models.Manager  
  2.   
  3. @{  
  4. ViewBag.Title = "ComplexDetails";  
  5. }  
  6.   
  7. <h2>ComplexDetails</h2>  
  8.   
  9.   
  10. @Html.DisplayFor(x => x.EmployeeManager)  
Run the application.



Now let's see how to render a strongly-typed view using DisplayForModel.

@Html.DisplatForModel()

Add a StronglyTypedDetails action method in the HomeController.
  1. public ActionResult StronglyTypedDetails(int id) 
    {  
  2. EmployeeDB empDB = new EmployeeDB();  
  3. Employee employees = empDB.Employees.Single(x => x.Id == id);  
  4. return View(employees);  
  5. }  
Add a strongly-typed view.



In the Strongly-typed view write the following:
  1. @model DisplayAndEditTemplates.Models.Employee  
  2.   
  3. @{  
  4. ViewBag.Title = "StronglyTypedDetails";  
  5. }  
  6.   
  7. <h2>StronglyTypedDetails</h2>  
@Html.DisplayForModel()

Run the application.



So, we have seen all the three Display templates available for rendering the required HTML. Now let's see how to render the required HTML for an Edit view.

@Html.Editor

In the HomeController write the following in the Edit action method.
  1. public ActionResult Edit(int id) 
    {  
  2. EmployeeDB empDB = new EmployeeDB();  
  3. ViewData["Employee"] = empDB.Employees.Single(x => x.Id == id);  
  4. return View();  
  5. }  


Write the following in the Edit view.
  1. @{  
  2. ViewBag.Title = "Edit";  
  3. }  
  4.   
  5. <h2>Edit</h2>  
@Html.Editor("Employee")

Run the application.



Let's see how to create an Editor Template for a view that returns a complex type back.

@Html.EditorFor()

Create a new action method in the HomeController and in that method create a new object manager class and pass it to the view.

  1. public ActionResult ComplexEdit() 
    {  
  2. Manager m = new Manager();  
  3. return View(m);  
  4. }  
Add a strongly-typed view.



Write the following in the ComplexEdit view.

  1. @model DisplayAndEditTemplates.Models.Manager  
  2.   
  3. @{  
  4. ViewBag.Title = "ComplexEdit";  
  5. }  
  6.   
  7. <h2>ComplexEdit</h2>  
  8.   
  9. @Html.EditorFor(x => x.EmployeeManager)  
Run the application.


We got the edit template for Aiden because in the Manager Class we passed the Id value of 1.



Now let's see how to create a strongly-typed edit view using an EditorForModel template.

@Html.EditorForModel()

Create a new action method in HomeController.
  1. public ActionResult StronglyTypedEdit(int id) 
    {  
  2. EmployeeDB empDB = new EmployeeDB();  
  3. Employee employee = empDB.Employees.Single(x => x.Id == id);  
  4. return View(employee);  
  5. }  
Add a strongly-typed view.



Write the following in the View.
  1. @model DisplayAndEditTemplates.Models.Employee  
  2.   
  3. @{  
  4. ViewBag.Title = "StronglyTypedEdit";  
  5. }  
  6.   
  7. <h2>StronglyTypedEdit</h2>  
@Html.EditorForModel()

Run the application.



In the output, EditorForModel generated an edit view for id 2.

Change the id from 2 to 3.



Summary

This article explained the two types of template HTML Helpers.

Download the source file from here.

I hope you like it.

Thank you

 

Up Next
    Ebook Download
    View all
    Learn
    View all