Reputation: 2655
I have a question regarding enums, basically I've created a localized enum drop down list to correctly disply the enums with localization.
But when i would like to show the selected enum later somewhere on another page, I don't get the localization anymore.
Any idea, or maybe anyone could give me a link to some html extension for displaying enums.
I have the following:
public enum Gender
{
[Display(ResourceType = typeof(Resources.Base), Name = "Male")]
M= 0,
[Display(ResourceType = typeof(Resources.Base), Name = "Female")]
F= 1,
}
in my view i have following:
@Html.LabelForModel(Model.Gender.ToString())
And in the controler i set:
Model.Gender = Gender.M
Instead of showing the Male from the base, i get "M" displayed.
Any idea how to solve this?
Upvotes: 1
Views: 3454
Reputation: 2655
Finally I solved my issue myself, I've created a custom html helper to display correctly the "display' annotation.
public static MvcHtmlString DisplayEnum(this HtmlHelper helper, Enum e)
{
string result = string.Empty;
var display = e.GetType()
.GetMember(e.ToString()).First()
.GetCustomAttributes(false)
.OfType<DisplayAttribute>()
.LastOrDefault();
if (display != null)
{
result = display.GetName();
}
return helper.Label(result);
}
Upvotes: 7
Reputation: 101701
You should use this code in your view:
@Html.LabelFor(m => m.Gender)
Because Display
attribute using by LabelFor
method to display your value.ToString
is just converting your enum value to a string.It doesn't have any information about your attributes.
Upvotes: 1