Monday 16 November 2009

Extending the ASP.NET MVC DropDownList Html helper

I'm currently using ASP.NET MVC v1.0 and came across the need to populate a drop down list complete with option groups via the Html.DropDownList helper class.  E.g.



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, where the key corresponds to the group name and the IEnumerable corresponds to the options in that group.  E.g.

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.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. thank you very much Richard for the code. It work perfectly and it saved me a lot of time!

    alex

    ReplyDelete
  3. Please reupload the source files

    ReplyDelete