Tiago
Tiago

Reputation: 3131

Localizing Enum entry on asp.net core

How can I localize the following enum entries on asp.net core? I found few issues on asp.net-core github repository ( https://github.com/aspnet/Mvc/pull/5185 ), but I can't find a proper way to do it.

Target enum:

public enum TestEnum
{
    [Display(Name = "VALUE1_RESX_ENTRY_KEY")]
    Value1,
    [Display(Name = "VALUE3_RESX_ENTRY_KEY")]
    Value2
}

CSHTML code block:

<select id="test" asp-items="Html.GetEnumSelectList<TestEnum>()">
</select>

Resource files:

enter image description here

Upvotes: 4

Views: 5261

Answers (3)

LazZiya
LazZiya

Reputation: 5729

I created a tag helper that localizes enums, you only need to pass the enum type and a delegate for the localizing method.

<select-enum 
    enum-type="typeof(TestEnum)" 
    selected-value="(int)TestEnum.Value1" 
    text-localizer-delegate="delegate(string s) { return Localizer[s].Value; }"
    name="testEnum">
</select-enum>

or if you are using a shared resource for localization:

<select-enum 
    enum-type="typeof(TestEnum)" 
    selected-value="(int)TestEnum.Value1" 
    text-localizer-delegate="delegate(string s) { return MyLocalizer.Text(s); }"
    name="testEnum">
</select-enum>

install from nugget:

Install-Package LazZiya.TagHelpers -Version 2.0.0

read more here

Upvotes: 2

Skuami
Skuami

Reputation: 1624

It seems to be a bug which will be fixed in 3.0.0: https://github.com/aspnet/Mvc/issues/7748

A server side workaround would be something like this:

private List<SelectListItem> GetPhoneStateEnumList()
{
    var list = new List<SelectListItem>();
    foreach (PhoneState item in Enum.GetValues(typeof(PhoneState)))
    {
        list.Add(new SelectListItem
        {
            Text = Enum.GetName(typeof(PhoneState), item),
            Value = item.ToString()
        });
    }
    return list.OrderBy(x => x.Text).ToList();
}

Upvotes: 2

Michal Vlk
Michal Vlk

Reputation: 39

I have the same issue. My workaround was to specify enum options explicitly:

<select asp-for="Gender" class="form-control">
    <option disabled selected>@Localizer["ChooseGender"]</option>
    <option value="0">@Localizer["Male"]</option>
    <option value="1">@Localizer["Female"]</option>
</select>

Upvotes: 1

Related Questions