The web development world is considering ASP.NET MVC seriously. Unlike ASP.NET Web Form controls, the Html Helpers are not rich for MVC but growing. Recently, I needed a DropDownListFor HTML Helper where we could simply pass the LINQ Expression for the model property (where the property is an enum type) and we wanted to let the helper create the HTML Select element with all enum values. When creating the select list, we wanted to show a meaningful string for Display Type, where a string could contain space, special character etc. Obviously, an enum value cannot contain space and special character etc. So, wanted to decorate some of the enum members with Description Attribute so that, the Select list can display those Description attribute as display field where the original enum member name would be used as Value field. Finally, we came up with a DropDownListFor overload HTML helper. I thought this tiny utility is worth sharing. So, here is what I came up with.
** I have used Screenshots for the code so that I could use visual elements to mark areas. Therefore you may not be able to copy the snippet directly from this page; the full working solution source code is attached, you can download and use the source code.
First, let me show you how to use this helper. We can define an enum type as follows. Please notice the Description Attribute on some of the enum members.
Ok, then, in your View page, you can use a snippet like this: (I have used Razor View Engine, but as you understand, it can be used with any other view engine)
This will result following Look:
|Generated HTML |
That's it. Now, when you submit your form, the FavouriteColor property will be submitted, you can capture this value from your Controller's action method as follows:
That's all about the usage. Now, you can look into the tiny overloaded Html Helper extension source code here: (the full source code with sample MVC application is attached)
Please feel free to share your comment.