Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将枚举值放入SelectList_C#_Asp.net Mvc_Enums - Fatal编程技术网

C# 如何将枚举值放入SelectList

C# 如何将枚举值放入SelectList,c#,asp.net-mvc,enums,C#,Asp.net Mvc,Enums,假设我有这样一个枚举(仅作为示例): 如果枚举的内容将来可能会更改,如何编写例程将这些值放入System.Web.Mvc.SelectList?我希望将每个枚举名称作为选项文本,将其值作为值文本,如下所示: <select> <option value="0">Horizontal</option> <option value="1">Vertical</option> <option value="2"&

假设我有这样一个枚举(仅作为示例):

如果枚举的内容将来可能会更改,如何编写例程将这些值放入System.Web.Mvc.SelectList?我希望将每个枚举名称作为选项文本,将其值作为值文本,如下所示:

<select>
    <option value="0">Horizontal</option>
    <option value="1">Vertical</option>
    <option value="2">Diagonal</option>
</select>
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
                              };
}

水平的
垂直的
对角线的
这是迄今为止我能想到的最好的:

 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);
 }
publicstaticselectlist GetDirectionSelectList()
{
数组值=Enum.GetValues(typeof(Direction));
列表项=新列表(值.Length);
foreach(值中的var i)
{
items.Add(新列表项)
{
Text=Enum.GetName(typeof(Direction),i),
Value=i.ToString()
});
}
返回新的选择列表(项目);
}

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

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

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

我已经有一段时间没有这样做了,但我认为这应该行得通

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

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

<select>
    <option value="0">Horizontal</option>
    <option value="1">Vertical</option>
    <option value="2">Diagonal</option>
</select>
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
                              };
}
populateViewData4SelectList
在查看(“创建”)和查看(“编辑”)之前调用,然后在视图中:

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


就这些

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

 public static IEnumerable<SelectListItem> GetEnumSelectList<T>()
        {
            return (Enum.GetValues(typeof(T)).Cast<T>().Select(
                enu => new SelectListItem() { Text = enu.ToString(), Value = enu.ToString() })).ToList();
        }
public静态IEnumerable GetEnumSelectList()
{
return(Enum.GetValues(typeof(T)).Cast().Select(
enu=>newselectListItem(){Text=enu.ToString(),Value=enu.ToString()})).ToList();
}
我最终会做一些翻译工作,这样Value=enu.ToString()将调用某个地方的内容。

或:

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

我想做一些与Dann的解决方案非常相似的事情,但我需要值为int,文本为枚举的字符串表示形式。这就是我想到的:

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();
    }
public静态IEnumerable GetEnumSelectList()
{
return(Enum.GetValues(typeof(T)).Cast().Select(e=>newselectListItem(){Text=Enum.GetName(typeof(T),e),Value=e.ToString()})).ToList();
}
公共静态SelectList到SelectList(此TEnum enumObj),其中TEnum:struct
{
如果(!typeof(TEnum).IsEnum)抛出新的ArgumentException(“需要枚举类型。”,“enumObj”);
var values=from TEnum e in Enum.GetValues(typeof(TEnum))选择新的{ID=(int)Enum.Parse(typeof(TEnum),e.ToString()),Name=e.ToString();
//var values=from TEnum e in Enum.GetValues(typeof(TEnum))选择新的{ID=e,Name=e.ToString()};
返回新的SelectList(值“ID”、“Name”、enumObj);
}
公共静态SelectList到SelectList(此TEnum enumObj,字符串selectedValue),其中TEnum:struct
{
如果(!typeof(TEnum).IsEnum)抛出新的ArgumentException(“需要枚举类型。”,“enumObj”);
var values=from TEnum e in Enum.GetValues(typeof(TEnum))选择新的{ID=(int)Enum.Parse(typeof(TEnum),e.ToString()),Name=e.ToString();
//var values=from TEnum e in Enum.GetValues(typeof(TEnum))选择新的{ID=e,Name=e.ToString()};
if(string.IsNullOrWhiteSpace(selectedValue))
{
返回新的SelectList(值“ID”、“Name”、enumObj);
}
其他的
{
返回新的SelectList(值“ID”、“Name”、selectedValue);
}
}
返回
枚举
.GetNames(typeof(ReceptionNumberType))
其中(i=>(ReceptionNumberType)(Enum.Parse(typeof(ReceptionNumberType),i.ToString())new
{
description=i,
value=(Enum.Parse(typeof(ReceptionNumberType),i.ToString())
});

在ASP.NET MVC 5.1中有一个新功能


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

枚举项目集合

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

在ASP.NET核心MVC中,这是通过以下方式完成的


我有很多enum选择列表,经过多次搜索和筛选,发现制作一个通用助手对我来说最合适。它返回索引或描述符作为Selectlist值,返回描述作为Selectlist文本:

枚举:

public enum Your_Enum
{
    [Description("Description 1")]
    item_one,
    [Description("Description 2")]
    item_two
}
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();
    }
}
助手:

public enum Your_Enum
{
    [Description("Description 1")]
    item_one,
    [Description("Description 2")]
    item_two
}
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();
    }
}
公共静态类选择列表
{
公共静态SelectList EnumSelectlist(bool index=false),其中TEnum:struct
{
返回新的SelectList(Enum.GetValues(typeof(TEnum)).Cast().Select(item=>new SelectListItem
{
Text=GetEnumDescription(项作为枚举),
Value=index?Convert.ToInt32(item.ToString():item.ToString()
}).ToList(),“值”,“文本”);
}
//注意:如果没有描述,则返回描述符
私有静态字符串GetEnumDescription(枚举值)
{
FieldInfo fi=value.GetType().GetField(value.ToString());
DescriptionAttribute[]attributes=(DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute),false);
if(attributes!=null&&attributes.Length>0)
返回属性[0]。说明;
其他的
返回值.ToString();
}
}
用法: 将索引的参数设置为“true”作为值:

var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>();
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true);
var descriptorsAsValue=selectlist.EnumSelectlist();
var指示值=SelectList.EnumSelectlist(真);

这是一个很大的复制品,还有很多其他的。谢谢!我考虑过这个,但认为可能有一种方法可以不用铸造。几乎可以,只需要一个小的改变!你
public enum Your_Enum
{
    [Description("Description 1")]
    item_one,
    [Description("Description 2")]
    item_two
}
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();
    }
}
var descriptorsAsValue = Selectlists.EnumSelectlist<Your_Enum>();
var indicesAsValue = Selectlists.EnumSelectlist<Your_Enum>(true);