2016-12-06 14 views
3

これは私の列挙です。列挙型表示属性の名前を表示する方法

public enum ContractType 
{ 
    [Display(Name = "Permanent")] 
    Permanent= 1, 

    [Display(Name = "Part Time")] 
    PartTime= 2, 

} 

次のコードを使用して表示名を取得しようとします。

string x = Enum.GetName(typeof(ContractType), 2); 

しかし、それは常に "非常勤" リターンです。実際には、私は表示属性の名前を取得したい。 上記の例ではxを割り当てる必要がありますパートタイム

巨大なコードを持つソリューションがあります。これには単純な/ 1行の解決策はありませんか?

私に指示をしてください。

+5

http://stackoverflow.com/questions/13099834/how-to-get-the-display-name- enum-member-via-mvc-razor-code – Valentin

答えて

8

はデータアノテーション表示名を取得する列挙

public enum ContractType 
{ 
    [Display(Name = "Permanent")] 
    Permanent= 1, 

    [Display(Name = "Part Time")] 
    PartTime //Automatically 2 you dont need to specify 
} 

カスタム方法を考えます。 GETDISPLAYNAMEを呼び出す

//This is a extension class of enum 
public static string GetEnumDisplayName(this Enum enumType) 
{ 
    return enumType.GetType().GetMember(enumType.ToString()) 
        .First() 
        .GetCustomAttribute<DisplayAttribute>() 
        .Name; 
} 

()

ContractType.Permanent.GetEnumDisplayName(); 

ホープ、このことができます:)

+1

'enum'はキーワードであり、有効なパラメータ名ではなく、' @ enum'にしてください。 'ContractType.PartTime'または' ContractType.Permanent'を使用するかどうかにかかわらず、最初のenum値は "Permanent"です。 – ColinM

関連する問題