如何从 EnumDropDownList 获取显示文本用于发布
本文关键字:文本 用于 显示 获取 EnumDropDownList | 更新日期: 2023-09-27 17:56:11
有没有办法从 EnumDropDownList 获取 DisplayName (Text) 对于枚举的助手?
枚举:
public enum PartnersGroup
{
[Display(Name="Partner_SystemsGroup",ResourceType=typeof(Global) )]
SystemsGroup,
[Display(Name="Partner_SoftwarePartners",ResourceType=typeof(Global))]
SoftwarePartners,
[Display(Name="Partner_IntegrationPartners",ResourceType=typeof(Global))]
IntegrationPartners,
}
型
public class Partner
{
public PartnersGroup PartnersGroup { get; set; }
}
控制器
// GET: Partners/Create
public ActionResult Create()
{
----
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Partner partner)
{
if (ModelState.IsValid)
{
// here model does not show language based text(shown in dropdown in view). Getting Enum value like "IntegrationPartners".
// In model parner.ParnerGroup shows IntegrationPartners, but it should be "Integration Partners" in English or "Partenaires d'intégration" in French.
// Save to DB
}
}
视图(创建)按预期显示键的基于语言的资源值。它工作正常。
@Html.EnumDropDownListFor(model => model.PartnersGroup)
请帮忙吗?
您可以为枚举编写一个扩展方法来返回 Enum 值Display
值:
public static class DataAnnotationHelpers
{
public static string GetDisplayValue(this Enum instance)
{
var fieldInfo = instance.GetType().GetMember(instance.ToString()).Single();
var descriptionAttributes = fieldInfo.GetCustomAttributes(typeof(DisplayAttribute), false) as DisplayAttribute[];
if (descriptionAttributes == null) return instance.ToString();
return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].GetName() : instance.ToString();
}
}
并像这样使用它:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Partner partner)
{
if (ModelState.IsValid)
{
var localizedDisplayName = partner.PartnersGroup.GetDisplayValue();
// Save to DB
}
}
近似解决方案是在合作伙伴类中添加 PartnersGroupString 属性 getter,以便将枚举转换为其本地化字符串。参见以下代码
public class Partner
{
public PartnersGroup PartnersGroup { get; set; }
[doNotGenerateIntoDatabase]
public string PartnersGroupString {
get{
return
Strings.ResourceManager.GetString("PartnersGroup_" + this.PartnersGroup);}
}
}
然后,您可以使用...model.PartnersGroupString