How can I display the custom names of my enums in dropdownlist in Razor? My current code is:
@Html.DropDownListFor(model => model.ExpiryStage,
new SelectList(Enum.GetValues(typeof(ExpiryStages))),
new { @class = "selectpicker" })
My enum is:
public enum ExpiryStages
{
[Display(Name = "None")]
None = 0,
[Display(Name = "Expires on")]
ExpiresOn = 1,
[Display(Name = "Expires between")]
ExpiresBetween = 2,
[Display(Name = "Expires after")]
ExpiresAfter = 3,
[Display(Name = "Current")]
Current = 4,
[Display(Name = "Expired not yet replaced")]
ExpiredNotYetReplaced = 5,
[Display(Name = "Replaced")]
Replaced = 6
}
For example, I want to display "Expired not yet replaced" instead of ExpiredNotYetReplaced in my DropDownList.
You could use ajax to post the value to the server and return the text value. Or you could pass a collection/dictionary or the enums int and name values to the view and convert it to a javascript array and search that array for the corresponding value.
The MVC framework sees the enum value as a simple primitive and uses the default string template. One solution to change the default framework behavior is to write a custom model metadata provider and implement GetMetadataForProperty to use a template with the name of "Enum" for such models.
From MVC 5.1, they have added this new helper. You just need an enum
public enum WelcomeMessageType
{
[Display(Name = "Prior to accepting Quote")]
PriorToAcceptingQuote,
[Display(Name = "After Accepting Quote")]
AfterAcceptingQuote
}
and you can create the dropdownlist showing the names by writing
@Html.EnumDropDownListFor(model => model.WelcomeMessageType, null, new { @id = "ddlMessageType", @class = "form-control", @style = "width:200px;" })
I have a enum extension to retrieve the display name.
public static string GetDescription<TEnum>(this TEnum value)
{
var attributes = value.GetAttributes<DescriptionAttribute>();
if (attributes.Length == 0)
{
return Enum.GetName(typeof(TEnum), value);
}
return attributes[0].Description;
}
Which you can use like this:
Enum.GetValues(typeof(ExpiryStages)).Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
I use a handy helper to generate select lists from enums:
public static SelectList SelectListFor<T>()
where T : struct
{
var t = typeof (T);
if(!t.IsEnum)
{
return null;
}
var values = Enum.GetValues(typeof(T)).Cast<T>()
.Select(e => new { Id = Convert.ToInt32(e), Name = e.GetDescription() });
return new SelectList(values, "Id", "Name");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With