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
- using DropDownListPostApp_MVC.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace DropDownListPostApp_MVC.Controllers
- {
- public class EmployeeController : Controller
- {
- EmployeeEntities objEmployeeEntities = new EmployeeEntities();
- public ActionResult Index()
- {
- ViewBag.List = new SelectList(objEmployeeEntities.Departments.Select(r => r.DepartmentName));
- return View();
- }
-
-
- [HttpPost]
- public string Index(string List)
- {
- if (string.IsNullOrEmpty(List))
- {
- return "Invalid Selection";
- }
- else
- {
- return "Selected Value is: " + List;
- }
- }
-
- }
- }
Adding View
Figure 7: Add View
Figure 8: View Index
Index.cshtml
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
- {
-
- @Html.DropDownList("List", "--------SELECT------")
-
- <br />
- <input type="submit" value="Submit" />
- }
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!