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

如何为ASP.NET MVC枚举值设置额外显示值?

解决方法

要实现后台下拉菜单显示首字母大写的状态名称,同时前端生成符合Bootstrap要求的全小写类名,只需要给枚举值添加[Display]特性指定显示文本即可,枚举的底层值保持小写不变,两边需求都能满足。

修改后的Model代码

先引用System.ComponentModel.DataAnnotations命名空间,再给每个枚举值配置显示名称:

using System.ComponentModel.DataAnnotations;

namespace SitefinityWebApp.Mvc.Models
{
    public enum AlertStatus
    {
        [Display(Name = "Primary")]
        primary, 
        [Display(Name = "Secondary")]
        secondary, 
        [Display(Name = "Success")]
        success, 
        [Display(Name = "Danger")]
        danger, 
        [Display(Name = "Warning")]
        warning, 
        [Display(Name = "Info")]
        info
    }
    public class AlertModel
    {
        public string AlertText { get; set; }
        public AlertStatus Enum { get; set; }
    }
}

原理说明

  • Sitefinity的部件编辑界面会读取[Display]特性的Name值,下拉菜单里会显示首字母大写的选项(比如Primary、Success)。
  • 枚举值传递到View时,@Model.Enum.ToString()依然输出原始小写值(比如primary、success),前端生成的类名还是alert-primary、alert-success,完全符合Bootstrap规范。

其他代码无需修改

你的Controller和View代码保持原样即可,功能会正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 18:55:27