DropDownList Helper to Handle HttpPost in MVC

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.   
  8. namespace DropDownListPostApp_MVC.Controllers  
  9. {  
  10.     public class EmployeeController : Controller  
  11.     {  
  12.         EmployeeEntities objEmployeeEntities = new EmployeeEntities();  
  13.         public ActionResult Index()  
  14.         {  
  15.             ViewBag.List = new SelectList(objEmployeeEntities.Departments.Select(r => r.DepartmentName));  
  16.             return View();  
  17.         }  
  18.   
  19.   
  20.         [HttpPost]  
  21.         public string Index(string List)  
  22.         {  
  23.             if (string.IsNullOrEmpty(List))  
  24.             {  
  25.                 return "Invalid Selection";  
  26.             }  
  27.             else  
  28.             {  
  29.                 return "Selected Value is: " + List;  
  30.             }  
  31.         }  
  32.   
  33.     }  
  34. }

Adding View


Figure 7: Add View


Figure 8: View Index 

Index.cshtml

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

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!


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