枚举到列表(Id,名称)

问题描述 投票:6回答:2

enum转换为Id / Name对象列表的最佳做法是什么?

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));
}
c# asp.net-mvc enums
2个回答
9
投票

使用LINQ

var typeList = Enum.GetValues(typeof(Type))
               .Cast<Type>()
               .Select(t => new TypeViewModel
               {
                   Id = ((int)t),
                   Name = t.ToString()
               });

结果:

enter image description here


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

© www.soinside.com 2019 - 2024. All rights reserved.