Unfortunately the Html helper class in MVC v1.0 doesn't currently support this so I had to write my own. There's probably a much quicker way of doing this but repeated googling failed to find it. Anyway, you need four files called GroupSelectList.cs, GroupSelectListItem.cs, GroupMultiSelectList.cs and GroupDropListExtensions.cs. The code for each can be found here:
http://www.filefactory.com/file/a1b8dd0/n/GroupMultiSelectList.cs
http://www.filefactory.com/file/a1b8dd1/n/GroupSelectList.cs
http://www.filefactory.com/file/a1b8dd2/n/GroupSelectListItem.cs
http://www.filefactory.com/file/a1b8ddh/n/GroupDropListExtensions.cs
Put these in your project, perhaps in a folder called HtmlHelperExtensions, but it doesn't really matter. Once compiled you will then be able to create a grouped dropdown list in the same way you would a regular dropdown list. The only difference is that when setting up your SelectList, instead of passing an IEnumerable of things to display, you pass a Dictionary
Controller file:
public ActionResult Index(){
var group1 = new List<string> {"apple", "pear"};
var group2 = new List<string> {"car", "bike"};
var dictionary = new Dictionary<string, IEnumerable> { {"First group", group1}, {"Second group", group2} };
ViewData["GroupedDropDown"] = new GroupSelectList(dictionary);
return View("Index");
}
View file
...
<%=Html.GroupDropDownList("Name", ViewData["GroupedDropDown"] as GroupDropDownList, "Select fruit or car...")%>
...
The above code would reproduce the dropdown list above.
This comment has been removed by the author.
ReplyDeletethank you very much Richard for the code. It work perfectly and it saved me a lot of time!
ReplyDeletealex
Please reupload the source files
ReplyDelete