I am using a jquery multiselect plugin [https://github.com/davidstutz/bootstrap-multiselect] and binding it dynamically with database values.
HTML
@Html.ListBoxFor(m => m.Classes, new SelectList(Model.Classes, "Value", "Text"), new { @id = "classList" })
SCRIPT
$('#classList').multiselect({ enableClickableOptGroups: true });
The model in the view is a view model and contains a property for a SelectList
public class SearchControlViewModel
{
....
public SelectList Classes { get; set; }
}
and the code in the controller
SearchControlViewModel model = new SearchControlViewModel()
{
....
Classes = new SelectList(repClass.GetClassesByYear(23), "classID", "classname")
};
return View(model);
It works like a charm except for one thing - I want to add grouping/group header like <optgroup>
does. How can I do that?
The GetClassesByYear()
method used for generating the SelectList
returns an object containing properties int classID
, string classname
and string grade
and I want to be able to group the options by grade
.
Option groups are not supported in MVC-4, and you would need to upgrade to MVC-5 to make use out-of-the-box functions. If you do upgrade, refer Constructing a Select List with OptGroup groups for examples using both the
SelectList
constructor, and by generating anIEnumerable<SelectListItem>
Without upgrading, you could pass a model representing your groups and their options to the view , and use some javascript/jquery to generate the elements. Start by creating some additional view models
Then modify your main view model to include the following
Note that your current model and use of
ListBoxFor()
is incorrect becauseyou cannot bind a
<select multiple>
to a collection of complex objects which yourClasses
property is - the model needs to be a collection of value types, andyou cannot use the same name for the property your binding to and the
SelectList
- refer Will there be any conflict if i specify the viewBag name to be equal to the model property name inside @Html.DropDownListFor for more detailIn the controller
And in the view use
which will initially generate the
<select>
without any options. Then use the following script to generate the options