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中。选择列表,考虑到枚举的内容将来可能会发生变化?我想让每个枚举名作为选项文本,其值作为值文本,如下所示:
This is the best I can come up with so far:
这是到目前为止我所能想到的最好的:
public static SelectList GetDirectionSelectList()
{
Array values = Enum.GetValues(typeof(Direction));
List items = new List(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()返回的是'Horizontal, Vertical'等等,而不是我预期的0,1,这让我想知道Enum.GetName()和Enum.GetValue()之间的区别是什么。
22
To get the value of an enum you need to cast the enum to its underlying type:
要获得enum的值,您需要将enum转换为其底层类型:
Value = ((int)i).ToString();
76
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);
35
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枚举
@Html.EnumDropDownListFor(model => model.Direction)
29
This is what I have just made and personally I think its sexy:
这就是我刚刚做的,我个人认为它很性感:
public static IEnumerable GetEnumSelectList()
{
return (Enum.GetValues(typeof(T)).Cast().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()将在某处调用一些东西。
16
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解决方案非常相似的事情,但是我需要值是int,文本是Enum的字符串表示。这就是我想到的:
public static IEnumerable GetEnumSelectList()
{
return (Enum.GetValues(typeof(T)).Cast().Select(e => new SelectListItem() { Text = Enum.GetName(typeof(T), e), Value = e.ToString() })).ToList();
}
4
Or:
或者:
foreach (string item in Enum.GetNames(typeof(MyEnum)))
{
myDropDownList.Items.Add(new ListItem(item, ((int)((MyEnum)Enum.Parse(typeof(MyEnum), item))).ToString()));
}
4
return
Enum
.GetNames(typeof(ReceptionNumberType))
.Where(i => (ReceptionNumberType)(Enum.Parse(typeof(ReceptionNumberType), i.ToString())) new
{
description = i,
value = (Enum.Parse(typeof(ReceptionNumberType), i.ToString()))
});
3
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
};
}
PopulateViewdata4Selectlists
is called before View("Create") and View("Edit"), then and in the View:
populateviewdata4selectlist在视图(“Create”)和视图(“Edit”)之前被调用,然后在视图中:
<%= Html.DropDownList("Fetcher") %>
and that's all..
这就是. .
3
public static SelectList ToSelectList(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(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);
}
}
3
In ASP.NET Core MVC this is done with tag helpers.
在ASP。NET Core MVC这是通过标记助手完成的。
1
I have more classes and methods for various reasons:
由于各种原因,我有更多的课程和方法:
Enum to collection of items
枚举到项目集合
public static class EnumHelper
{
public static List EnumToCollection()
{
return (Enum.GetValues(typeof(T)).Cast().Select(
e => new ItemViewModel
{
IntKey = e,
Value = Enum.GetName(typeof(T), e)
})).ToList();
}
}
Creating selectlist in Controller
在控制器中创建selectlist
int selectedValue = 1; // resolved from anywhere
ViewBag.Currency = new SelectList(EnumHelper.EnumToCollection(), "Key", "Value", selectedValue);
MyView.cshtml
MyView.cshtml
@Html.DropDownListFor(x => x.Currency, null, htmlAttributes: new { @class = "form-control" })
0
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选择列表,在进行了大量搜索和筛选之后,我发现让通用助手最适合我。它返回索引或描述符作为Selectlist值,描述作为Selectlist文本:
Enum:
枚举:
public enum Your_Enum
{
[Description("Description 1")]
item_one,
[Description("Description 2")]
item_two
}
Helper:
助手:
public static class Selectlists
{
public static SelectList EnumSelectlist(bool indexed = false) where TEnum : struct
{
return new SelectList(Enum.GetValues(typeof(TEnum)).Cast().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:
用法:将指标参数设置为“true”为值:
var descriptorsAsValue = Selectlists.EnumSelectlist();
var indicesAsValue = Selectlists.EnumSelectlist(true);