DisplayTextFor Helper Handle HttpPost in MVC

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.   
  9. namespace DisplayTextForMVCPost_App.Controllers  
  10. {  
  11.     public class EmployeeController : Controller  
  12.     {  
  13.   
  14.         EmployeeEntities db = new EmployeeEntities();  
  15.         //  
  16.         // GET: /Employee/  
  17.         public ActionResult Index()  
  18.         {  
  19.             return View(db.Departments.ToList());  
  20.         }  
  21.   
  22.         [HttpPost]  
  23.         public string Index(IEnumerable<Department> dpt)  
  24.         {  
  25.             StringBuilder sb = new StringBuilder();  
  26.             foreach (var item in dpt)  
  27.             {  
  28.                 sb.Append("The list of departments: <b>" + item.DepartmentName + "</b>");  
  29.                 sb.Append("<br />");  
  30.             }  
  31.   
  32.             return sb.ToString();  
  33.         }  
  34.     }  
  35. }  

Add a View as Figure 9.

 
Figure 9: Add Index View

Index.cshtml

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

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!


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.