C# 如何将枚举的值放入 SelectList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1110070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 08:28:06  来源:igfitidea点击:

How to get the values of an enum into a SelectList

c#asp.net-mvcenums

提问by Lee D

Imagine I have an enumeration such as this (just as an example):

想象一下,我有一个这样的枚举(仅作为示例):

public enum Direction{
    Horizontal = 0,
    Vertical = 1,
    Diagonal = 2
}

How can I write a routine to get these values into a System.Web.Mvc.SelectList, given that the contents of the enumeration are subject to change in future? I want to get each enumerations name as the option text, and its value as the value text, like this:

考虑到枚举的内容将来可能会发生变化,我如何编写一个例程来将这些值放入 System.Web.Mvc.SelectList 中?我想将每个枚举名称作为选项文本,并将其值作为值文本,如下所示:

<select>
    <option value="0">Horizontal</option>
    <option value="1">Vertical</option>
    <option value="2">Diagonal</option>
</select>

This is the best I can come up with so far:

这是迄今为止我能想到的最好的:

 public static SelectList GetDirectionSelectList()
 {
    Array values = Enum.GetValues(typeof(Direction));
    List<ListItem> items = new List<ListItem>(values.Length);

    foreach (var i in values)
    {
        items.Add(new ListItem
        {
            Text = Enum.GetName(typeof(Direction), i),
            Value = i.ToString()
        });
    }

    return new SelectList(items);
 }

However this always renders the option text as 'System.Web.Mvc.ListItem'. Debugging through this also shows me that Enum.GetValues() is returning 'Horizontal, Vertical' etc. instead of 0, 1 as I would've expected, which makes me wonder what the difference is between Enum.GetName() and Enum.GetValue().

然而,这总是将选项文本呈现为“System.Web.Mvc.ListItem”。通过这个调试也告诉我 Enum.GetValues() 正在返回 'Horizo​​ntal, Vertical' 等,而不是我所期望的 0, 1,这让我想知道 Enum.GetName() 和 Enum 之间有什么区别。获取值()。

采纳答案by Andrew Hare

To get the value of an enum you need to cast the enum to its underlying type:

要获取枚举的值,您需要将枚举转换为其基础类型:

Value = ((int)i).ToString();

回答by Brandon

It's been awhile since I've had to do this, but I think this should work.

自从我不得不这样做已经有一段时间了,但我认为这应该有效。

var directions = from Direction d in Enum.GetValues(typeof(Direction))
           select new { ID = (int)d, Name = d.ToString() };
return new SelectList(directions , "ID", "Name", someSelectedValue);

回答by Carl H?rberg

maybe not an exact answer to the question, but in CRUD scenarios i usually implements something like this:

也许不是这个问题的确切答案,但在 CRUD 场景中,我通常会实现如下内容:

private void PopulateViewdata4Selectlists(ImportJob job)
{
   ViewData["Fetcher"] = from ImportFetcher d in Enum.GetValues(typeof(ImportFetcher))
                              select new SelectListItem
                              {
                                  Value = ((int)d).ToString(),
                                  Text = d.ToString(),
                                  Selected = job.Fetcher == d
                              };
}

PopulateViewdata4Selectlistsis called before View("Create") and View("Edit"), then and in the View:

PopulateViewdata4Selectlists在 View("Create") 和 View("Edit") 之前调用,然后在 View 中调用:

<%= Html.DropDownList("Fetcher") %>

and that's all..

就这样..

回答by Dan

This is what I have just made and personally I think its sexy:

这是我刚刚做的,我个人认为它很性感:

 public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
        {
            return (Enum.GetValues(typeof(T)).Cast<T>().Select(
                enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
        }

I am going to do some translation stuff eventually so the Value = enu.ToString() will do a call out to something somewhere.

我最终会做一些翻译的东西,所以 Value = enu.ToString() 会调用某个地方的东西。

回答by zkarolyi

Or:

或者:

foreach (string item in Enum.GetNames(typeof(MyEnum)))
{
    myDropDownList.Items.Add(new ListItem(item, ((int)((MyEnum)Enum.Parse(typeof(MyEnum), item))).ToString()));
}

回答by J.Noel.K

I wanted to do something very similar to Dann's solution, but I needed the Value to be an int and the text to be the string representation of the Enum. This is what I came up with:

我想做一些与 Dann 的解决方案非常相似的事情,但我需要 Value 是一个 int 并且文本是 Enum 的字符串表示。这就是我想出的:

public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
    {
        return (Enum.GetValues(typeof(T)).Cast<int>().Select(e => new SelectListItem() { Text = Enum.GetName(typeof(T), e), Value = e.ToString() })).ToList();
    }

回答by Joao Leme

    public static SelectList ToSelectList<TEnum>(this TEnum enumObj) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");

        var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
        //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() };

        return new SelectList(values, "ID", "Name", enumObj);
    }
    public static SelectList ToSelectList<TEnum>(this TEnum enumObj, string selectedValue) where TEnum : struct
    {
        if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");

        var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = (int)Enum.Parse(typeof(TEnum), e.ToString()), Name = e.ToString() };
        //var values = from TEnum e in Enum.GetValues(typeof(TEnum)) select new { ID = e, Name = e.ToString() };
        if (string.IsNullOrWhiteSpace(selectedValue))
        {
            return new SelectList(values, "ID", "Name", enumObj);
        }
        else
        {
            return new SelectList(values, "ID", "Name", selectedValue);
        }
    }

回答by Hamid

return
            Enum
            .GetNames(typeof(ReceptionNumberType))
            .Where(i => (ReceptionNumberType)(Enum.Parse(typeof(ReceptionNumberType), i.ToString())) < ReceptionNumberType.MCI)
            .Select(i => new
            {
                description = i,
                value = (Enum.Parse(typeof(ReceptionNumberType), i.ToString()))
            });

回答by Fred

There is a new feature in ASP.NET MVC 5.1 for this.

为此,ASP.NET MVC 5.1 中有一个新功能。

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

http://www.asp.net/mvc/overview/releases/mvc51-release-notes#Enum

@Html.EnumDropDownListFor(model => model.Direction)

回答by Miroslav Holec

I have more classes and methods for various reasons:

由于各种原因,我有更多的类和方法:

Enum to collection of items

枚举到项目集合

public static class EnumHelper
{
    public static List<ItemDto> EnumToCollection<T>()
    {
        return (Enum.GetValues(typeof(T)).Cast<int>().Select(
            e => new ItemViewModel
                     {
                         IntKey = e,
                         Value = Enum.GetName(typeof(T), e)
                     })).ToList();
    }
}

Creating selectlist in Controller

在控制器中创建选择列表

int selectedValue = 1; // resolved from anywhere
ViewBag.Currency = new SelectList(EnumHelper.EnumToCollection<Currency>(), "Key", "Value", selectedValue);

MyView.cshtml

我的视图.cshtml

@Html.DropDownListFor(x => x.Currency, null, htmlAttributes: new { @class = "form-control" })