Geeks With Blogs
Scott Wojan DotRant BLOG

public static MvcHtmlString DropDownListFromEnumFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression, object htmlAttribute = null)

{

    var type = typeof (TProperty);

    var addBlank = false;

    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))

    {

        type = type.GetGenericArguments()[0];

        addBlank = true;

    }

    var values = (from f in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static)

                                    let attribute = f.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true).FirstOrDefault() as System.ComponentModel.DescriptionAttribute

                                    select new

                                    {

                                        Text = attribute == null ? f.Name : attribute.Description,

                                        Value = f.Name

                                    }).ToList();

    if (addBlank)

        values.Insert(0, new {Text = String.Empty, Value = String.Empty});

 

    return helper.DropDownListFor(expression,new SelectList(values, "Value", "Text"), htmlAttribute);

}

 

Will take…

public enum Salutation

{

    [Description("Mr.")]

    Mr = 100,

    [Description("Mr.")]

    Ms = 101,

    [Description("Mrs.")]

    Mrs = 102,

    [Description("Miss")]

    Miss = 103

}

And convert it to…

<select id="Suffix" name="Suffix">

  <option value="Junior">Junior</option>

  <option value="Senior">Senior</option>

  <option value="First">First</option>

  <option value="Second">Second</option>

  <option value="Third">Third</option>

  <option value="Fourth">Fourth</option>

  <option value="Fifth">Fifth</option>

</select>

Or if it’s a nullable property…

<select id="Suffix" name="Suffix">

  <option value=""></option>

  <option value="Junior">Junior</option>

  <option value="Senior">Senior</option>

  <option value="First">First</option>

  <option value="Second">Second</option>

  <option value="Third">Third</option>

  <option value="Fourth">Fourth</option>

  <option value="Fifth">Fifth</option>

</select>

 

 

Posted on Wednesday, March 13, 2013 5:07 PM | Back to top

Copyright © Scott Wojan | Powered by: GeeksWithBlogs.net