Introduction

This article shows how to use a dropdownlist helper to handle HttpPost in MVC applications.

Create an ASP.Net Web Application


Figure 1: New Project

Choose MVC template


Figure 2: MVC Template

Set up an Entity Framework


Figure 3: Entity Framework

Add an Employee Controller


Figure 4: Employee Controller


Figure 5: MVC 5 Controller

Figure 6: Add Controller

EmployeeController.cs

  1. using DropDownListPostApp_MVC.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace DropDownListPostApp_MVC.Controllers
  8. {
  9. public class EmployeeController : Controller
  10. {
  11. EmployeeEntities objEmployeeEntities = new EmployeeEntities();
  12. public ActionResult Index()
  13. {
  14. ViewBag.List = new SelectList(objEmployeeEntities.Departments.Select(r => r.DepartmentName));
  15. return View();
  16. }
  17. [HttpPost]
  18. public string Index(string List)
  19. {
  20. if (string.IsNullOrEmpty(List))
  21. {
  22. return "Invalid Selection";
  23. }
  24. else
  25. {
  26. return "Selected Value is: " + List;
  27. }
  28. }
  29. }
  30. }

Adding View


Figure 7: Add View


Figure 8: View Index

Index.cshtml

  1. @{
  2. ViewBag.Title = "Index";
  3. }
  4. <h2>Index</h2>
  5. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
  6. {
  7. @Html.DropDownList("List", "--------SELECT------")
  8. <br />
  9. <input type="submit" value="Submit" />
  10. }

The following screenshot shows the output of the application.


Figure 9: Output


Figure 10: Invalid Selection

Figure 11: Index

Figure 12:
Final Output

Summary

In this article we saw how to use a dropdownlist helper to handle HttpPost in MVC application.
Happy coding!