1

I am using the following editor template to create drop downs from enums.

It works great. But if possible I'd like to use the DisplayName or Description attributes as a text value, so that the user sees "My Selection" as opposed to "MySelection".

Is this possible?

I have a feeling it might not be because it's a generic enum template, not specific to the type. I'm wondering if there is some reflection magic I can use to achieve this.

@model Enum

@{
    var htmlAttributesFromView = ViewData["htmlAttributes"] ?? new { };
    var htmlAttributes = Html.MergeHtmlAttributes(htmlAttributesFromView, new { @class = "form-control" });
}


@{

    var values = Enum.GetValues(ViewData.ModelMetadata.ModelType).Cast<object>()
                     .Select(v => new SelectListItem
                        {
                            Selected = v.Equals(Model),
                            Text = v.ToString(),
                            Value = v.ToString()
                        });
}
<div class="form-group">
    @Html.LabelFor(model => model, htmlAttributes: new { @class = "control-label col-md-3" })
    <div class="col-md-8">
        @Html.DropDownListFor(model => model, values, "Please Select...", htmlAttributes)
        @Html.ValidationMessageFor(model => model)
    </div>
    <a class="infoonclick col-md-1" title="@Html.DisplayNameFor(model => model)" data-content="@Html.DescriptionFor(model => model)">
        <span class="fa fa-info-circle"></span>
    </a>
</div>
Martin Hansen Lennox
  • 2,837
  • 2
  • 23
  • 64

0 Answers0