如何将枚举值设置为ASP.MVC 5中的下拉列表,c#

时间:2017-07-19 14:25:03

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

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

 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);
        }

1 个答案:

答案 0 :(得分:1)

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

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