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
- using DisplayTextForMVCPost_App.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Web;
- using System.Web.Mvc;
-
- namespace DisplayTextForMVCPost_App.Controllers
- {
- public class EmployeeController : Controller
- {
-
- EmployeeEntities db = new EmployeeEntities();
-
-
- public ActionResult Index()
- {
- return View(db.Departments.ToList());
- }
-
- [HttpPost]
- public string Index(IEnumerable<Department> dpt)
- {
- StringBuilder sb = new StringBuilder();
- foreach (var item in dpt)
- {
- sb.Append("The list of departments: <b>" + item.DepartmentName + "</b>");
- sb.Append("<br />");
- }
-
- return sb.ToString();
- }
- }
- }
Add a View as Figure 9.
Figure 9: Add Index View
Index.cshtml
- @model IList<DisplayTextForMVCPost_App.Models.Department>
-
- @{
- Layout = null;
- }
-
- @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
- {
-
- for (int i = 0; i < Model.Count; i++)
- {
- @Html.HiddenFor(m => m[i].DepartmentName)
- @Html.DisplayTextFor(m => m[i].DepartmentName)
- <br />
- }
- <br />
- <input type="submit" value="Submit" />
- }
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!