利用顯示名稱增強 ASP.NET MVC Razor 視圖中的枚舉表示
使用 [Display]
屬性來豐富枚舉成員可以在 Razor 視圖中更清晰、更用戶友好地呈現枚舉值。這種方法簡化了所選枚舉數據的顯示。
利用擴展方法進行屬性檢索
直接在 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>
在 Razor 視圖中實現擴展
此擴展簡化了對 Razor 視圖中顯示屬性的訪問:
<code class="language-csharp">@foreach (int aPromotion in Enum.GetValues(typeof(UserPromotion))) { var currentPromotion = (int)Model.JobSeeker.Promotion; if ((currentPromotion & aPromotion) == aPromotion) { var displayAttribute = currentPromotion.GetAttribute<DisplayAttribute>(); <li>@displayAttribute?.GetName()</li> } }</code>
此代碼迭代枚舉值,識別與模型屬性的匹配,並使用擴展來檢索顯示名稱。 @displayAttribute?.GetName()
安全地處理空值並訪問顯示名稱。
此擴展方法提供了一種在 Razor 視圖中訪問和顯示枚舉顯示名稱的簡化方法,提高了 ASP.NET MVC 應用程序的清晰度和用戶體驗。
以上是如何使用ASP.NET MVC中的Razor語法訪問枚舉名稱?的詳細內容。更多資訊請關注PHP中文網其他相關文章!