将enum
转换为ID /名称对象列表的最佳做法是什么?
Enum
:
public enum Type
{
Type1= 1,
Type2= 2,
Type3= 3,
Type4= 4
}
Object
:
public class TypeViewModel
{
public int Id { get; set; }
public string Name { get; set; }
}
类似的东西:
var typeList = new List<TypeViewModel>();
foreach (Type type in Enum.GetValues(typeof(Type)))
{
typeList.Add(new TypeViewModel(type.Id, type.Name));
}
答案 0 :(得分:9)
使用LINQ:
var typeList = Enum.GetValues(typeof(Type))
.Cast<Type>()
.Select(t => new TypeViewModel
{
Id = ((int)t),
Name = t.ToString()
});
结果:
答案 1 :(得分:1)
让我们说:
public enum Gender
{
Male = 0,
Female = 1
}
模特:
public class Person
{
public int Id {get; set;}
public string FullName {get; set;}
public Gender Gender {get; set;}
}
在视图中,您只需使用:
@model YourNameSpaceWhereModelsAre.Person;
...
@Html.BeginForm(...)
{
@Html.HiddenFor(model => model.Id);
@Html.EditorFor(model => model.FullName);
@Html.EnumDropDownListFor(m => Model.Gender);
<input type="submit"/>
}
您可以找到更多信息或MSDN