You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在CSHTML中如何显示枚举名称而非枚举ID?

解决枚举在ASP.NET Core视图中显示ID而非名称的问题

问题场景

定义了如下枚举:

using System.ComponentModel;
using System;
using System.Collections.Generic;
namespace eVote.Data.Enums
{
    public enum Positions
    {
        CEO =1,
        ProductManager,
         CTO,
         SalesManager,
        FinanceManager,
         HR,
        Accountant
    }
}

在添加功能的CSHTML中用Html.GetEnumSelectList生成下拉框正常,但在Index页面通过<td>@candidate.position</td>仅显示枚举的数字ID,而非枚举名称。

解决方案

方法1:直接使用Enum.GetName

在视图中直接调用Enum.GetName方法获取枚举的原始名称:

<td>@Enum.GetName(typeof(eVote.Data.Enums.Positions), candidate.position)</td>

这种方法简单直接,适合不需要自定义显示文本的场景。

方法2:结合Display属性与DisplayFor(支持友好名称)

如果需要将ProductManager这类枚举名显示为Product Manager这类带空格的友好文本,先给枚举成员添加[Display]属性:

using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations; // 需添加此命名空间
namespace eVote.Data.Enums
{
    public enum Positions
    {
        [Display(Name = "CEO")]
        CEO =1,
        [Display(Name = "Product Manager")]
        ProductManager,
        [Display(Name = "CTO")]
        CTO,
        [Display(Name = "Sales Manager")]
        SalesManager,
        [Display(Name = "Finance Manager")]
        FinanceManager,
        [Display(Name = "HR")]
        HR,
        [Display(Name = "Accountant")]
        Accountant
    }
}

然后在视图中使用Html.DisplayFor渲染:

<td>@Html.DisplayFor(modelItem => candidate.position)</td>

这种方法灵活性更高,能满足自定义显示文本的需求。

方法3:编写扩展方法(提升复用性)

如果项目中多个视图都需要处理枚举显示,可以编写一个扩展方法:

using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

public static class EnumExtensions
{
    public static string GetDisplayName(this Enum enumValue)
    {
        return enumValue.GetType()
            .GetMember(enumValue.ToString())
            .FirstOrDefault()?
            .GetCustomAttribute<DisplayAttribute>()?
            .Name ?? enumValue.ToString();
    }
}

之后在视图中直接调用:

<td>@candidate.position.GetDisplayName()</td>

这种方法适合频繁处理枚举显示的场景,代码复用性更强。


内容的提问来源于stack exchange,提问作者Sergiu BRC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 02:41:03