In this article I will explain with an example, how to implement Grouped DropDownList using HTML OptGroup element in ASP.Net MVC Razor.
The Grouped DropDownList will be populated from database using Entity Framework in ASP.Net MVC Razor.
In HTML DropDownList OptGroup element, which is used to Group items (options) of a DropDownList while in MVC, the Grouping of DropDownList items (options) is done using SelectListItem class and SelectListGroup class.
 
 
Database
In order to populate DropDownList with Parent Child relationship, I have made use of two tables namely VehicleTypes and VehicleSubTypes. The schema and the data present in both the tables are as follows.
VehicleTypes
Implement Grouped DropDownList using OptGroup in ASP.Net MVC
 
Implement Grouped DropDownList using OptGroup in ASP.Net MVC
 
VehicleSubTypes
Implement Grouped DropDownList using OptGroup in ASP.Net MVC
 
Implement Grouped DropDownList using OptGroup in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Creating an Entity Data Model
The very first step is to create an ASP.Net MVC Application and connect it to the Database using Entity Framework. For more details please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example.
Following is the Entity Data Model of the VehicleTypes and the VehicleSubTypes tables which will be used later in this project.
Implement Grouped DropDownList using OptGroup in ASP.Net MVC
 
 
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, first the records from the database are fetched using Entity Framework.
Then a nested loop is executed over the records VehicleTypes and VehicleSubTypes tables, where the VehicleTypes are used to create a SelectListGroup item and the VehicleSubTypes are used to create the SelectListItem where the Group property is assigned with the respective Group.
Finally the Generic List of SelectListItem class is returned to the View.
 
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
Note: This example uses Model class object for capturing Form field values, for more details please refer my article ASP.Net MVC: Form Submit (Post) example.
 
When the Form is submitted, the posted values are captured through the Request.Form collection.
The values of VehicleId and VehicleName are fetched and are set into a TempData object which will be later displayed in View using JavaScript Alert Message Box.
public class HomeController : Controller
{
    // GET: Home
    public  ActionResult Index()
    {
        List<SelectListItem> items = new List<SelectListItem>();
        VehiclesEntities entities = new VehiclesEntities();
 
        //Loop and add the Parent Nodes.
        foreach (VehicleType type in entities.VehicleTypes)
        {
            //Create the Group.
            SelectListGroup group = new SelectListGroup() { Name = type.Name };
 
            //Loop and add the Items.
            foreach (VehicleSubType subType in entities.VehicleSubTypes.Where(v => v.VehicleTypeId == type.Id))
            {
                items.Add(new SelectListItem
                {
                    Value = subType.Id.ToString(),
                    Text = subType.Name,
                    Group = group
                });
            }
        }
 
        return View(items);
    }
 
    [HttpPost]
    public ActionResult Submit(FormCollection formcollection)
    {
        TempData["Message"] = "Vehicle Name: " + formcollection["VehicleName"];
        TempData["Message"] += "\\nVehicle Id: " + formcollection["VehicleId"];
        return RedirectToAction("Index");
    }
}
 
 
View
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Submit.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The Form consists of a DropDownList, a Hidden Field and a Submit Button.
The DropDownList is generated using the Html.DropDownList Helper method.
The first parameter is the Name attribute of the DropDownList.
The second parameter is the Model object for populating the DropDownList i.e. its source of data.
The third parameter is the text of the Default Item of the DropDownList. If not specified there will be no default item in the DropDownList.
Finally, the fourth and the last parameter allows to specify the HTML attributes such as id, class etc.
The DropDownList has been assigned a jQuery OnChange event handler, when an item is selected in the DropDownList, the Text of the selected item is copied in the Hidden Field.
When the Submit Button is clicked, the Form gets submitted and the VehicleId and VehicleName values are sent to the Controller.
Finally, the VehicleId and VehicleName values of the selected Vehicle are displayed using JavaScript Alert Message Box.
@model IEnumerable<SelectListItem>
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    @using (Html.BeginForm("Submit", "Home", FormMethod.Post))
    {
        @Html.DropDownList("VehicleId", Model, "Please select", new { @id = "ddlVehicles" })
        @Html.Hidden("VehicleName", null, new { @id = "hfVehicleName" })
        <input type="submit" value="Submit"/>
    }
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $("body").on("change", "#ddlVehicles", function () {
            $("#hfVehicleName").val($(this).find("option:selected").text());
        });
    </script>
    @if (TempData["Message"] != null)
    {
        <script type="text/javascript">
            $(function () {
                alert("@TempData["Message"]");
            });
        </script>
    }
</body>
</html>
 
 
Screenshot
Implement Grouped DropDownList using OptGroup in ASP.Net MVC
 
 
Downloads