首頁 > 後端開發 > C++ > 如何使用ASP.NET MVC中的Razor語法訪問枚舉名稱?

如何使用ASP.NET MVC中的Razor語法訪問枚舉名稱?

DDD
發布: 2025-01-27 09:21:09
原創
900 人瀏覽過

How Can I Access Enum Display Names Using Razor Syntax in ASP.NET MVC?

利用顯示名稱增強 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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板