Select List Grouping with MVC
Option Groups allow you to add groupings to your select lists, this is a handy organisation feature to improve lengthy drop down lists.
<optgroup label="Item Group">
<option value="itemvalue">Item Text</option>
<option value="itemvalue2">Item Text 2</option>
Prior to MVC 5.2 if you wanted to output the above mark up you had to implement the helper function yourself, but now the out of the box editor templates support option groups.
The helper function works in the exact same way as before all that needs to be changed is the way the Select List items are built before being bound. There is a group property on the Select List item class that takes a SelectListGroup item. This allows you to specify one or more groupings and then add the items to each one as follows.
ModelClass model = new ModelClass();
List<SelectListItem> items = new List<SelectListItem>();
SelectListGroup group = new SelectListGroup();
group.Name = "Item Group";
SelectListItem li = new SelectListItem();
li.Text = "Item Text";
li.Value = "itemvalue";
li.Group = group;
model.ListItems = items;
The helper function will detect that the groups are present and automatically wrap your options with an optgroup tag.
@Html.DropDownListFor(model => model.SelectedListItem, Model.ListItems)PrevUpgrading Umbraco NextException logging in MVC with log4net