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

如何获取Asp.NET API的Enum枚举值用于React下拉组件?

解决Asp.NET + React中枚举作为下拉选项的简洁方案

方案1:在现有资源接口中附带枚举选项

不需要新增单独端点,在返回Item列表(或其他相关接口)的响应里,额外加入枚举的所有键值对。这样前端一次请求就能拿到业务数据和枚举选项,减少网络请求次数。

后端实现(Asp.NET)

先定义一个包含枚举选项的响应模型,再在接口中生成枚举数据:

// 通用枚举选项模型
public class EnumOption
{
    public string Value { get; set; }
    public string Label { get; set; }
}

// 包装Item列表和枚举选项的响应类
public class ItemsWithEnumResponse
{
    public List<Item> Items { get; set; } = new();
    public List<EnumOption> ItemTypeOptions { get; set; } = new();
}

// 在接口中处理
[HttpGet]
public IActionResult GetItems()
{
    // 从数据库获取Item列表
    var items = _dbContext.Items.ToList();
    
    // 生成ItemType枚举的键值对
    var itemTypeOptions = Enum.GetValues<ItemType>()
        .Select(type => new EnumOption
        {
            Value = type.ToString(),
            Label = type.ToString() // 如果需要显示友好名称,可结合DescriptionAttribute
        })
        .ToList();
    
    var response = new ItemsWithEnumResponse
    {
        Items = items,
        ItemTypeOptions = itemTypeOptions
    };
    
    return Ok(response);
}

如果需要给枚举值设置友好显示名称,可以给枚举成员加[Description]特性,再通过反射读取:

// 给Enum添加Description
public enum ItemType
{
    [Description("充电板")]
    ChargeBoard,
    [Description("液晶显示屏")]
    LCD,
    // ...其他成员
}

// 读取Description的扩展方法
public static string GetDescription(this Enum enumValue)
{
    var fieldInfo = enumValue.GetType().GetField(enumValue.ToString());
    var descriptionAttribute = fieldInfo?.GetCustomAttribute<DescriptionAttribute>();
    return descriptionAttribute?.Description ?? enumValue.ToString();
}

// 生成选项时替换Label
Label = type.GetDescription()

前端实现(React)

拿到响应中的itemTypeOptions后,直接渲染下拉组件:

import { useState } from 'react';

const ItemCreateForm = ({ itemTypeOptions }) => {
    const [selectedType, setSelectedType] = useState('');

    return (
        <div>
            <label>选择物品类型:</label>
            <select
                value={selectedType}
                onChange={(e) => setSelectedType(e.target.value)}
                required
            >
                <option value="">请选择</option>
                {itemTypeOptions.map(opt => (
                    <option key={opt.Value} value={opt.Value}>
                        {opt.Label}
                    </option>
                ))}
            </select>
        </div>
    );
};

export default ItemCreateForm;

方案2:利用Swagger/OpenAPI自动生成前端枚举代码

如果你的API已经集成了Swagger,Asp.NET会自动将枚举信息写入OpenAPI文档。可以用代码生成工具(如openapi-generator)自动生成包含枚举定义的前端代码,后端枚举变更时,重新生成即可,无需手动同步。

步骤:

  1. 确保Asp.NET项目启用Swagger,枚举会被自动识别并加入API文档。
  2. 安装openapi-generator:
    npm install @openapitools/openapi-generator-cli -g
    
  3. 执行命令生成前端TypeScript代码(以React Query为例):
    openapi-generator-cli generate \
      -i http://localhost:5000/swagger/v1/swagger.json \
      -g typescript-react-query \
      -o src/api
    
  4. 生成的代码中会包含ItemType枚举,直接在React组件中使用:
import { ItemType } from '../api/models';

// 渲染下拉选项
<select>
    {Object.values(ItemType).map(type => (
        <option key={type} value={type}>
            {type}
        </option>
    ))}
</select>

方案3:通用枚举查询端点

如果项目中有多个枚举需要前端使用,可以创建一个通用端点,根据枚举名称返回对应的选项,不用为每个枚举单独写接口。

后端实现:

[HttpGet("enum/{enumName}")]
public IActionResult GetEnumValues(string enumName)
{
    // 替换为你的命名空间,比如"YourProject.Domain.Enums"
    var fullEnumName = $"YourProject.Domain.Enums.{enumName}";
    var enumType = Type.GetType(fullEnumName);
    
    if (enumType == null || !enumType.IsEnum)
    {
        return BadRequest("无效的枚举名称");
    }

    var enumOptions = Enum.GetValues(enumType)
        .Cast<Enum>()
        .Select(e => new EnumOption
        {
            Value = e.ToString(),
            Label = e.GetDescription() // 用之前的扩展方法获取友好名称
        })
        .ToList();

    return Ok(enumOptions);
}

前端调用:

// 封装获取枚举的函数
const fetchEnumOptions = async (enumName) => {
    const res = await fetch(`/api/enum/${enumName}`);
    return res.json();
};

// 在组件中使用
useEffect(() => {
    fetchEnumOptions("ItemType").then(options => {
        setItemTypeOptions(options);
    });
}, []);

方案对比

  • 方案1:适合枚举仅与特定资源绑定的场景,简单直接,减少请求次数。
  • 方案2:适合有完善API文档的项目,自动化程度高,彻底避免前后端枚举不一致。
  • 方案3:适合多枚举场景,复用性强,一次实现支持所有枚举。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 01:30:27