有没有办法从枚举的EnumDropDownListFor helper中获取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)
请帮忙吗?
答案 0 :(得分:1)
您可以为Enums编写扩展方法,以返回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
}
}
答案 1 :(得分:0)
近似解决方案是在合作伙伴类中添加PartnersGroupString属性getter,以便将枚举转换为其本地化字符串。见下面的代码
public class Partner
{
public PartnersGroup PartnersGroup { get; set; }
[doNotGenerateIntoDatabase]
public string PartnersGroupString {
get{
return
Strings.ResourceManager.GetString("PartnersGroup_" + this.PartnersGroup);}
}
}
然后您可以使用... model.PartnersGroupString