Introduction

This article shows you how to use a DisplayTextfor helper to handle HttpPost operations 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

Setup Entity Framework as shown in Figures 3, 4 and 5.


Figure 3: Add ADO.NET Entity Framework


Figure 4: Connection setting


Figure 5: Select Tables

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


Figure 6: Add controller


Figure 7: MVC controller - empty


Figure 8: EmployeeController

EmployeeController.cs

  1. using DisplayTextForMVCPost_App.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. namespace DisplayTextForMVCPost_App.Controllers
  9. {
  10. public class EmployeeController : Controller
  11. {
  12. EmployeeEntities db = new EmployeeEntities();
  13. //
  14. // GET: /Employee/
  15. public ActionResult Index()
  16. {
  17. return View(db.Departments.ToList());
  18. }
  19. [HttpPost]
  20. public string Index(IEnumerable<Department> dpt)
  21. {
  22. StringBuilder sb = new StringBuilder();
  23. foreach (var item in dpt)
  24. {
  25. sb.Append("The list of departments: <b>" + item.DepartmentName + "</b>");
  26. sb.Append("<br />");
  27. }
  28. return sb.ToString();
  29. }
  30. }
  31. }

Add a View as Figure 9.


Figure 9: Add Index View

Index.cshtml

  1. @model IList<DisplayTextForMVCPost_App.Models.Department>
  2. @{
  3. Layout = null;
  4. }
  5. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
  6. {
  7. for (int i = 0; i < Model.Count; i++)
  8. {
  9. @Html.HiddenFor(m => m[i].DepartmentName)
  10. @Html.DisplayTextFor(m => m[i].DepartmentName)
  11. <br />
  12. }
  13. <br />
  14. <input type="submit" value="Submit" />
  15. }

The output of the application is as in Figure 10.


Figure 10: Index

Summary

In this article we saw how to use a DisplayTextFor Helper to handle HttpPost operations in MVC application.
Happy coding!