monkeySeeMonkeyDo
monkeySeeMonkeyDo

Reputation: 391

Incorrect Enum localisation via String.Format()

I cannot get String.Format() to use localisation for an enumeration. It will not pick up the default localisation, and instead, always defaults to French. My site is French. English translations are in Title.en-GB.resx.

I have the following enum:

public enum Title
{
     [Display(Name = "Mr", ResourceType = typeof(Res.Title))]
     Mr = 1,
     [Display(Name = "Mrs", ResourceType = typeof(Res.Title))]
     Mrs = 2,
     [Display(Name = "Miss", ResourceType = typeof(Res.Title))]
     Miss = 3
}

I am using two simple resource files (English and French) that do this:

<data name="Miss" xml:space="preserve">
  <value>Mademoiselle</value>
</data>

The translations work as expected when I am doing this:

@Html.EnumDropDownListFor(m => m.Title)

However, whenever I am trying to display the enum via String.Format, the translation never wants to work, and I always end up with Mister or Madame etc.

<p>
    @String.Format("{0} {1} {2}", (Title)Model.Person.Title), Model.Person.FirstName, Model.Person.LastName)
</p>

Title is an int on the model hence the cast.

The web.config has the following setting:

<globalization uiCulture="fr-FR" culture="fr-FR" />

Everything else is fine. Any ideas? Thanks.

Upvotes: 1

Views: 116

Answers (1)

Vladimir
Vladimir

Reputation: 3822

The reason why it happens is that string.Format will call ((Title)Model.Person.Title).ToString() method and this method doesn't know anything about Display attribute. In such case you need to get the value somehow. One of the methods is create some extension like:

public static class EnumExtensions
{
    public static string GetDisplayName(this Enum value)
    {
        return value.GetType()
            .GetMember(value.ToString())
            .First()
            .GetCustomAttribute<DisplayAttribute>()
            .GetName();
    }
}

where .GetName() will retrieve localized string from resources

Then you should call it:

<p>
    @String.Format("{0} {1} {2}", ((Title)Model.Person.Title).GetDisplayName(), Model.Person.FirstName, Model.Person.LastName)
</p>

Upvotes: 1

Related Questions