How to create Dropdown list using Option group in MVC Razor syntax in View, like below iimage
Any code or tutorial link? Thanks
First, you need to create a List or get of items from the database, here in this example we will show the below data list item
public static List<Car> GetCars()
{
return new List<Car>{
new Car{Id=1, Name="Volvo", Category="Swedish Cars"},
new Car{Id=2, Name="Mercedes-Benz", Category="German Cars"},
new Car{Id=3, Name="Saab", Category="Swedish Cars"},
new Car{Id=4, Name="Audi", Category="German Cars"},
new Car{Id=5, Name="Audi", Category="German Cars"},
};
}
Car class C# Code
public class Car
{
public int Id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
}
In your Controller, you can create SelectListItem using the above Cars data as
public ActionResult Index()
{
//Here Category is served as OptionGroup for dropdown list
ViewBag.OptGroupCarList= new SelectList(Car.GetCars(), "Id", "Name","Category",1);
return View();
}
SelectList have 3 more overloaded constructors which take the grouping field name as one of the parameters. Here is a snapshot of the constructors supported by SelectList:
In the above C# code, Id maps to data value field, Name maps to data text field and Category maps to data group field, and selected item = 1
In the View, You can use the ViewBag.OptGroupCarList as
<h3>HTML OptGroup Razor Demo</h3>
@Html.DropDownList("OptGroupCarList")
That's it you are done.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly