ASP.NET MVC has an HTML Helper DropDownListFor that takes an IEnumerable and creates a drop down list for it. Often you want to create a drop down list for an Enum. Of course you can do this without using an HTML Helper and use standard HTML controls but you don’t have the standard clean view code that HTML Helpers give you. Extending and creating your own HTML Helpers is rather easy, as demonstrated in my last post. With that in mind I created an extension to DropDownListFor that will create a drop down list for an Enum type.
Note: Because enumeration values have to adhere to the same naming conventions as variables I had to work some magic to get the display values formatted correctly. OK, it’s really not magic…just a little RegEx Voo-Doo.
The code is available on GitHub
Keith is a Senior Software Engineer with Falafel Software. He has been developing software since 1999 specializing in web-based solutions primarily using the Microsoft stack. He has been a Microsoft MVP in ASP.NET since 2012.
The opinions expressed herein are my own personal opinions and do not represent
my employer's view in any way.