11

What is the best practice to convert an enum to an list of Id/Name-objects?

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

Something like:

var typeList = new List<TypeViewModel>();
foreach (Type type in Enum.GetValues(typeof(Type)))
{
    typeList.Add(new TypeViewModel(type.Id, type.Name));
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Palmi
  • 2,381
  • 5
  • 28
  • 65

2 Answers2

27

Use LINQ:

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

Result:

enter image description here

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
2

Let's say we have :

public enum Gender
{
   Male = 0,
   Female = 1
}

And model :

public class Person 
{
   public int Id {get; set;}
   public string FullName {get; set;}
   public Gender Gender {get; set;}
}

In view you can simply use :

@model YourNameSpaceWhereModelsAre.Person;

... 

@Html.BeginForm(...)
{
   @Html.HiddenFor(model => model.Id);
   @Html.EditorFor(model => model.FullName);
   @Html.EnumDropDownListFor(m => Model.Gender);

   <input type="submit"/>
}

More information you can find or MSDN

Fabjan
  • 13,506
  • 4
  • 25
  • 52
  • How is the selected Gender posted? – Palmi May 05 '16 at 17:39
  • Well, you don't really need to think about it, it's where the magic of helper method comes. Just send model to view where one of its properties is enum, use `EnumDropDownListFor()` inside the form get the model back with submitted request to your `Post` method of controller and work with model. – Fabjan May 05 '16 at 17:43
  • I accepted S.Akbari's answer because I asked for a list, but your way seems the better way to do this in my case. – Palmi May 05 '16 at 17:47
  • Well, if you work with older version of Asp.Net MVC then Abari's answer is the only way to go but in new versions i like this 'magic' helper methods that we can use. – Fabjan May 05 '16 at 17:51