问题
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