Localizing Enum entry on asp.net core

允我心安 提交于 2021-02-07 08:17:53

问题


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:


回答1:


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();
}



回答2:


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




回答3:


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>


来源:https://stackoverflow.com/questions/42236478/localizing-enum-entry-on-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!