【问题标题】:How to set enum values to dropdown in ASP.MVC 5, c#如何在 ASP.MVC 5 中将枚举值设置为下拉列表,c#
【发布时间】:2017-07-19 14:25:02
【问题描述】:

我有需要在下拉列表中设置的枚举值,但我无法这样做。

 public static List<SelectListItem> GetDraft(int selectedGroupId)
{
    List<SelectListItem> data = new List<SelectListItem>();
    // attempt 1 
    data.Add(new SelectListItem() { Value = Hello.SIM, Text = "Create New Draft" });
                                               ^^ I want the value to be "2", compile time error as Value can only be string

    // attempt 2 
    data.Add(new SelectListItem() { Value = Hello.SIM.ToString(), Text = "Create New Draft" });
                                               ^^ I want the value to be "2" but now it comes out to be string as "SIM"
    // below are some other values that I need to set and they are working as expected as they are not ENUM
    // some code has been removed for brevity
    foreach (dsSimSettings.DraftRow row in draftData.Rows)
    {
        data.Add(new SelectListItem() { Value = row.idDraft.ToString(), Text = row.strDescription });
    }
    return data;
}

public enum Hello
{
   SIM = 2
}

编辑

[AuthorizeSettings]
        public JsonResult GetDrafts(int groupId)
        {
            List<SelectListItem> drafts = SecurityHelper.GetDraft(groupId);
            return Json(drafts);
        }

【问题讨论】:

  • 您如何/在哪里使用GetDraft 方法?
  • @Béranger:添加了编辑
  • 我只需要一个枚举,就是这样。其余所有下拉菜单都很好。只有第一个需要是 ENUM,我希望值为“2”。
  • 你试过Hello.SIM.ToString()
  • @FailedUnitTest:检查我的尝试 2,在代码 sn-p 中提供。它以“SIM”而不是“2”的形式给出值

标签: c# asp.net-mvc drop-down-menu enums asp.net-mvc-5


【解决方案1】:

您可以使用以下方法转换枚举值:

((int)Hello.SIM).ToString()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多