如何将枚举的值放入 SelectList 中

发布于 2024-07-26 20:40:33 字数 1049 浏览 1 评论 0原文

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

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

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

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

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

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

但是,这总是将选项文本呈现为“System.Web.Mvc”。项目清单'。 通过此调试还显示 Enum.GetValues() 返回“水平、垂直”等,而不是我预期的 0、1,这让我想知道 Enum.GetName() 和 Enum 之间有什么区别。获取值()。

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:

<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().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

夏九 2024-08-02 20:40:33

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

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

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);
晚雾 2024-08-02 20:40:33

ASP.NET MVC 5.1 中为此提供了一个新功能。

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

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

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

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

@Html.EnumDropDownListFor(model => model.Direction)
情仇皆在手 2024-08-02 20:40:33

这就是我刚刚制作的,我个人认为它很性感:

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

我最终将做一些翻译工作,这样 Value = enu.ToString() 就会在某个地方调用某些东西。

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.

呆萌少年 2024-08-02 20:40:33

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

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

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

Value = ((int)i).ToString();
孤云独去闲 2024-08-02 20:40:33

我想做一些与 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();
    }

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:

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();
    }
等往事风中吹 2024-08-02 20:40:33

在 ASP.NET Core MVC 中,这是通过 标签助手< 完成的/a>.

<select asp-items="Html.GetEnumSelectList<Direction>()"></select>

In ASP.NET Core MVC this is done with tag helpers.

<select asp-items="Html.GetEnumSelectList<Direction>()"></select>
过期情话 2024-08-02 20:40:33

也许不是问题的确切答案,但在 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
                              };
}

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

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

就这样..

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

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

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

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

and that's all..

白鸥掠海 2024-08-02 20:40:33

或者:

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

Or:

foreach (string item in Enum.GetNames(typeof(MyEnum)))
{
    myDropDownList.Items.Add(new ListItem(item, ((int)((MyEnum)Enum.Parse(typeof(MyEnum), item))).ToString()));
}
ゃ人海孤独症 2024-08-02 20:40:33
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()))
            });
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()))
            });
你げ笑在眉眼 2024-08-02 20:40:33
    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);
        }
    }
    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);
        }
    }
世俗缘 2024-08-02 20:40:33

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

枚举项目集合

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

在控制器中创建选择列表

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

MyView.cshtml

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

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

@Html.DropDownListFor(x => x.Currency, null, htmlAttributes: new { @class = "form-control" })
如日中天 2024-08-02 20:40:33

我有很多枚举选择列表,经过大量搜索和筛选后,发现制作通用助手最适合我。 它返回索引或描述符作为选择列表值,以及描述作为选择列表文本:

Enum:

public enum Your_Enum
{
    [Description("Description 1")]
    item_one,
    [Description("Description 2")]
    item_two
}

Helper:

public static class Selectlists
{
    public static SelectList EnumSelectlist<TEnum>(bool indexed = false) where TEnum : struct
    {
        return new SelectList(Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(item => new SelectListItem
        {
            Text = GetEnumDescription(item as Enum),
            Value = indexed ? Convert.ToInt32(item).ToString() : item.ToString()
        }).ToList(), "Value", "Text");
    }

    // NOTE: returns Descriptor if there is no Description
    private static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}

Usage:
将索引参数设置为“true”作为值:

var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>();
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true);

I had many enum Selectlists and, after much hunting and sifting, found that making a generic helper worked best for me. It returns the index or descriptor as the Selectlist value, and the Description as the Selectlist text:

Enum:

public enum Your_Enum
{
    [Description("Description 1")]
    item_one,
    [Description("Description 2")]
    item_two
}

Helper:

public static class Selectlists
{
    public static SelectList EnumSelectlist<TEnum>(bool indexed = false) where TEnum : struct
    {
        return new SelectList(Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Select(item => new SelectListItem
        {
            Text = GetEnumDescription(item as Enum),
            Value = indexed ? Convert.ToInt32(item).ToString() : item.ToString()
        }).ToList(), "Value", "Text");
    }

    // NOTE: returns Descriptor if there is no Description
    private static string GetEnumDescription(Enum value)
    {
        FieldInfo fi = value.GetType().GetField(value.ToString());
        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attributes != null && attributes.Length > 0)
            return attributes[0].Description;
        else
            return value.ToString();
    }
}

Usage:
Set parameter to 'true' for indices as value:

var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>();
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true);
<逆流佳人身旁 2024-08-02 20:40:33

您可以使用此帮助器将枚举类转换为值和显示名称列表(您必须之前编写 GetDisplalyName 扩展):

 public static List<SelectListItem> ToSelectList<T>() where T : Enum
 {
    return (Enum.GetValues(typeof(T)).Cast<T>()
        .Select(e => new SelectListItem() {
            Text = e.GetDisplayName(),
            Value = Convert.ToInt16(e).ToString(),
        }))
        .ToList();
 }

you can use this helper for convert the enum class to List of value and display name (you have to write the GetDisplalyName extension before):

 public static List<SelectListItem> ToSelectList<T>() where T : Enum
 {
    return (Enum.GetValues(typeof(T)).Cast<T>()
        .Select(e => new SelectListItem() {
            Text = e.GetDisplayName(),
            Value = Convert.ToInt16(e).ToString(),
        }))
        .ToList();
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文