2014-03-01 103 views
0

考慮枚舉使用枚舉顯示名稱

公共枚舉教育 {

 [Display(Name="display for education 1")] 
Education1, 

    [Display(Name="display for education 2")] 
    Education2, 

    [Display(Name="display for education 3")] 
    Education3,   
} 

現在,我想有一個用上述顯示值下降

@Html.DropDownListFor(
    model => model.Education, 
    new SelectList(@Enum.GetValues(typeof(Education))) 
    new {@class = "default"} 
) 

我想要顯示名稱(目前我得到的是枚舉字符串本身。 有人知道如何在.cshtml中提取該文件?

回答

1

看看這個

public static string[] GetEnumDisplays(Type type) 
    { 
     var displays = new List<string>(); 
     foreach (FieldInfo f in type.GetFields(BindingFlags.Public | BindingFlags.Static)) 
     { 
      object[] attr = f.GetCustomAttributes(typeof(DisplayAttribute), false); 
      if (attr.Length != 0) 
      { 
       var displayAttribute = (DisplayAttribute)attr[0]; 
       displays.Add(displayAttribute.Name); 
      } 
      else 
      { 
       displays.Add(f.Name); 
      } 
     } 

     return displays.ToArray(); 
    }