Introduction

This article shows how to use a DisplayTextFor helper in MVC applications.

Create an ASP.Net Web Application as in Figure 1.

Figure 1: Web application

Choose MVC template as in Figure 2.

Figure 2: MVC template

Set up Entity Framework as in Figures 3 and 4.

Figure 3: Add ADO.NET Entity Framework

Figure 4: Connection setting

Figure 5: Select tables

Add an Employee Controller as in Figures 6, 7 and 8.

Figure 6: Add controller

Figure 7: MVC controller - empty

Figure 8: EmployeeController

EmployeeController.cs

  1. using DisplayTextForMVC_App.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace DisplayTextForMVC_App.Controllers
  8. {
  9. public class EmployeeController : Controller
  10. {
  11. EmployeeEntities db = new EmployeeEntities();
  12. //
  13. // GET: /Employee/
  14. public ActionResult Index()
  15. {
  16. return View(db.Departments.ToList());
  17. }
  18. }
  19. }
Add the View as in Figure 9.

Figure 9: Add Index View

Index.cshtml

  1. @model IEnumerable<DisplayTextForMVC_App.Models.Department>
  2. @{
  3. Layout = null;
  4. }
  5. @foreach (var item in Model)
  6. {
  7. @Html.DisplayTextFor(model => item.DepartmentName)
  8. <br />
  9. }
The output of the application is as in the following:

Figure 10: Index

Summary

In this article we saw how to use a DisplayTextFor helper in MVC applications.
Happy coding!