Convert Enum to SelectList

Share on Facebook

Simple extension method to convert enumeration to a selectList for use with MVC DropDownList.

       
        public static SelectList ToSelectList(this Enum enumeration)
        {
            var list = (from Enum d in Enum.GetValues(enumeration.GetType())
                        select new { ID = (int)Enum.Parse(enumeration.GetType(),    Enum.GetName(enumeration.GetType(), d)), Name = d.ToString() }).ToList();
            return new SelectList(list, "ID", "Name");
        }

Say you have an enumeration depicted in the code below:

 
 public enum Options
 {
    option1= 1,
    option2= 2,
    option3=3
 }     

You will use the above extension in this way:

 
 SelectList Selections;
 Options opts = new Options();
 Selections = opts.ToSelectList();
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkListkick it on DotNetKicks.comTwitThis

Comments are closed

About Me

When not scratching my head for solutions to software challenges, I spend my time playing with my little boy - Michael Jnr.

Quotations

"A fanatic is one who can't change his mind and won't change the subject."
Sir Winston Churchill

Donate with PayPal - it

Calendar

<<  February 2012  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
2728291234
567891011

View posts in large calendar

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2005 - 2012

Search