MVC Razor ビュー内で列挙型表示名を効率的に表示するには、属性メタデータにアクセスする必要があります。 これは、リフレクションを活用したカスタム拡張メソッドを使用してエレガントに処理できます。
次の拡張メソッドはクリーンなソリューションを提供します:
<code class="language-csharp">public static TAttribute GetAttribute<TAttribute>(this Enum enumValue) where TAttribute : Attribute { return enumValue.GetType() .GetMember(enumValue.ToString()) .First() .GetCustomAttribute<TAttribute>(); }</code>
このメソッドは、リフレクションを使用して列挙型を調べ、指定された列挙値に一致する列挙メンバーに関連付けられた指定された型 (TAttribute
) の最初の属性を取得します。
この拡張メソッドを Razor ビューに統合する方法は次のとおりです。
<code class="language-csharp">@foreach (int aPromotion in Enum.GetValues(typeof(UserPromotion))) { var currentPromotion = (int)Model.JobSeeker.Promotion; if ((currentPromotion & aPromotion) == aPromotion) { <p>@((UserPromotion)aPromotion).GetAttribute<DisplayAttribute>().Name</p> } }</code>
このコードは、UserPromotion
列挙値を反復処理します。 Model.JobSeeker.Promotion
プロパティ (フラグ列挙型であると仮定) に存在する各値について、拡張メソッドを使用して DisplayAttribute
の Name
プロパティを取得し、表示します。 これにより、選択した列挙値のみがわかりやすい表示名で表示されます。
以上がMVCかみそりビューで列挙名を取得する方法は?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。