Enum to List<Object> (Id, Name)

12,196

Solution 1

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

Solution 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

Share:
12,196
Palmi
Author by

Palmi

Updated on June 04, 2022

Comments

  • Palmi
    Palmi almost 2 years

    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));
    }
    
  • Palmi
    Palmi almost 8 years
    How is the selected Gender posted?
  • Fabjan
    Fabjan almost 8 years
    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.
  • Palmi
    Palmi almost 8 years
    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.
  • Fabjan
    Fabjan almost 8 years
    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.