MVC's EnumDropDownListFor html helper does not render Description and ShortName attributes. I needed custom attribute texts for rendered option tags. I searched a lot not to re-write everything in about MVC but i couldnt find any.
I know MVC is very different apart from WebForms but, MVC should have provided a way for customizing renderin mechanism.
Based on my searches, i first needed to read all members of Enum type and then, rewrite renderering mechanism containing validation. The worst option to modify base method's html was to use regex. The result code looks like below:
public static MvcHtmlString EnumDropDownListForEx<T, TProperty>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TProperty>> expression,
object htmlAttributes, string placeholder = "")
{
var type = Nullable.GetUnderlyingType(typeof(TProperty)) ?? typeof(TProperty);
var values = Enum.GetValues(type);
var name = ExpressionHelper.GetExpressionText(expression);
var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
var select = new TagBuilder("select");
select.MergeAttribute("name", fullHtmlFieldName);
select.MergeAttributes(new RouteValueDictionary(htmlAttributes));
var option = new TagBuilder("option");
option.MergeAttribute("value", "");
option.MergeAttribute("selected", "selected");
option.InnerHtml = placeholder;
var sb = new StringBuilder();
sb.Append(option.ToString(TagRenderMode.Normal));
foreach (Enum value in values)
{
option = new TagBuilder("option");
option.MergeAttribute("value", value.ToInt().ToString());
option.InnerHtml = value.GetEnumDescription();
var attr = value.GetAttribute<DisplayAttribute>();
if(attr == null)
continue;
option.InnerHtml = attr.Name;
option.MergeAttribute("description", attr.Description);
option.MergeAttribute("shortname", attr.ShortName);
sb.Append(option.ToString(TagRenderMode.Normal));
}
select.InnerHtml = sb.ToString();
select.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name));
return MvcHtmlString.Create(select.ToString(TagRenderMode.Normal));
}