1

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?

1
  • I'm still, looking for an answer, if anyone can ...? Commented Jan 6, 2014 at 10:33

2 Answers 2

7

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);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

you get name, but i dont think you get resource for that name, did you?
@deadManN read the docs
1

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.

1 Comment

Now instead of M, I get Gender, but I need to see "Male" or localized version of it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.