DropDownList problem with Enums
I am currently localizing an open source project and I have a problem with Enums.
Here is my Enums.cs (not the whole file, just part of where the problem appears).
public enum ModeratorLevel
{
[Display(Name = "Sahip")]
Owner = 1,
[Display(Name = "Moderatör")]
Moderator = 2,
[Display(Name = "Temizlikçi")]
Janitor = 3,
[Display(Name = "Boyacı")]
Designer = 4,
[Display(Name = "Paylaşımcı")]
Submitter = 99
}
and this is my view (again, not the whole file, only contains the codes that I want to fix)
@{
string subverseName = ViewBag.SubverseName;
var levelsAvailable = Enum.GetValues(typeof(ModeratorLevel)).OfType<ModeratorLevel>();
var currentLevel = ModeratorPermission.Level(User.Identity.Name, subverseName);
levelsAvailable = levelsAvailable.Where(x => x > currentLevel || currentLevel == ModeratorLevel.Owner);
}
@* these areas contain other codes is not related to my issue *@
<div class="form-group">
@Html.Label("foo", htmlAttributes: new {@class = "control-label col-md-2"})
<div class="col-md-4">
@Html.DropDownListFor(model => model.Power, levelsAvailable.Select(x => new SelectListItem() { Text = x.ToString(), Value = ((int)x).ToString() }), new { @class = "form-control"} )
@Html.ValidationMessageFor(model => model.Power, "", new {@class = "text-danger"})
</div>
</div>
@* these areas contain other codes is not related to my issue *@
and it is displayed; drop-down list
aaand now what i want? I want to display DisplayNames values, not Enum values. An attempt looks like this:
- foo = Owner
- Leading
- Janitor
- Constructor
- Sender
But I want to show that it looks like this:
- foo = Sahip
- MODERATOR
- Temizlikçi
- Boyacı
- Paylaşımcı
But in this change, the changes should only be visual. We shouldn't change any code that affects the Enum function. I just want to show only DisplayNames values instead of Enum values.
Thank.
+3
source to share
2 answers
you can add extension method:
public static string DisplayName(this Enum value)
{
Type enumType = value.GetType();
var enumValue = Enum.GetName(enumType, value);
MemberInfo member = enumType.GetMember(enumValue)[0];
var attrs = member.GetCustomAttributes(typeof(DisplayAttribute), false);
var outString = ((DisplayAttribute)attrs[0]).Name;
if (((DisplayAttribute)attrs[0]).ResourceType != null)
{
outString = ((DisplayAttribute)attrs[0]).GetName();
}
return outString;
}
and then use it in the view:
@Html.DropDownListFor(model => model.Power, levelsAvailable.Select(x => new SelectListItem() { Text = x.DisplayName(), Value = ((int)x).ToString() }), new { @class = "form-control"} )
+1
source to share