Asp Asp
Asp Asp

Reputation: 874

Display enum in dropdown with Html.DropdownListFor

in a model file I have

public enum Title
{
   Ms,
   Mrs,
   Mr
}

I would like to display on the register form's downdown box these selectable values.

But I don't know how. It doesn't necessarily require me to use an enum, provided those titles could be in use with dropdownlistfor, please you can suggest me any methods. Thank you.

Upvotes: 0

Views: 1229

Answers (5)

Lulu
Lulu

Reputation: 1

I'm late too but I struggled a bit with the same thing so I hope it might be of help to someone else.

I had a View called "InscriptionPartenaire" in which I wanted to put a form with a dropdownlist. The enum class (called "StatutJuridique") I wanted to use was in Models, in a file called Enums.

@Html.DropDownListFor(model => model.StatutJuridique, Enum.GetValues(typeof(StatutJuridique)).Cast<StatutJuridique>().Select(
            x => new SelectListItem { Text = x.ToString().Replace("_", " "), Value = x.ToString() }), "Statut juridique", new { @class = "input-field" })

I replaced the "_" in my enum list, "Statut juridique", new { @class = "input-field" }) is to have "Statut juridique" to appear by default and "input-field" is my css class.

Don't forget the namespace above your View or else it won't work.

Upvotes: 0

Walter Torricos
Walter Torricos

Reputation: 381

A little late but you can just use the Html helpers:

@Html.GetEnumSelectList<Title>()

Upvotes: 0

GHP
GHP

Reputation: 3231

I use a combination of things. First off, here's an extension method for Enums to get all enum items in a collection from an enum type:

public static class EnumUtil
{
    public static IEnumerable<T> GetEnumValuesFor<T>()
    {
        return Enum.GetValues(typeof(T)).Cast<T>();
    }
}

Then, I have some code to turn a List into a List. You can indicate which of the values you are passing in are already Selected (just 1 for a Dropdown list, but you can use this to power a CheckBoxList as well), as well has indicating ones to exclude too, if necessary.

public static List<SelectListItem> GetEnumsByType<T>(bool useFriendlyName = false, List<T> exclude = null,
            List<T> eachSelected = null, bool useIntValue = true) where T : struct, IConvertible
        {
            var enumList = from enumItem in EnumUtil.GetEnumValuesFor<T>()
                           where (exclude == null || !exclude.Contains(enumItem))
                           select enumItem;

            var list = new List<SelectListItem>();

            foreach (var item in enumList)
            {
                var selItem = new SelectListItem();

                selItem.Text = (useFriendlyName) ? item.ToFriendlyString() : item.ToString();
                selItem.Value = (useIntValue) ? item.To<int>().ToString() : item.ToString();

                if (eachSelected != null && eachSelected.Contains(item))
                    selItem.Selected = true;

                list.Add(selItem);
            }

            return list;
        }

        public static List<SelectListItem> GetEnumsByType<T>(T selected, bool useFriendlyName = false, List<T> exclude = null,
            bool useIntValue = true) where T : struct, IConvertible
        {
            return GetEnumsByType<T>(
                useFriendlyName: useFriendlyName,
                exclude: exclude,
                eachSelected: new List<T> { selected },
                useIntValue: useIntValue
            );
        }

And then in my View Model, when I need to fill a DropdownList, I can just grab the List from that helper method like so:

public class AddressModel
{

     public enum OverrideCode
        {
            N,
            Y,
        }

     public List<SelectListItem> OverrideCodeChoices { get {
         return SelectListGenerator.GetEnumsByType<OverrideCode>();
     } }
}

Upvotes: 0

Colin Bacon
Colin Bacon

Reputation: 15609

There are a couple of methods to this.

One is to create a method that returns a select list.

private static SelectList ToSelectList(Type enumType, string selectedItem)
{
    var items = new List<SelectListItem>();
    foreach (var item in Enum.GetValues(enumType))
    {
        var title = ((Enum)item).GetDescription();
        var listItem = new SelectListItem
        {
            Value = ((int)item).ToString(),
            Text = title,
            Selected = selectedItem == item.ToString()
        };
        items.Add(listItem);
    }

    return new SelectList(items, "Value", "Text");
}

The second method is to create helper method

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string optionLabel, object htmlAttributes)
{
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
    Type enumType = GetNonNullableModelType(metadata);
    IEnumerable<TEnum> values = Enum.GetValues(enumType).Cast<TEnum>();

    IEnumerable<SelectListItem> items = from value in values
                                        select new SelectListItem
                                        {
                                            Text = GetEnumDescription(value),
                                            Value = value.ToString(),
                                            Selected = value.Equals(metadata.Model)
                                        };

    // If the enum is nullable, add an 'empty' item to the collection 
    if (metadata.IsNullableValueType)
    {
        items = SingleEmptyItem.Concat(items);
    }

    return htmlHelper.DropDownListFor(expression, items, optionLabel, htmlAttributes);
}

public static string GetEnumDescription<TEnum>(TEnum value)
{
    FieldInfo fi = value.GetType().GetField(value.ToString());

    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);

    if ((attributes != null) && (attributes.Length > 0))
    {
        return attributes[0].Description;
    }

    return value.ToString();
}

Upvotes: 1

MethodMan
MethodMan

Reputation: 18843

you can bind it like this

ddl.DataSource = Enum.GetNames(typeof(Title));
ddl.DataBind();

if you want to get the selected value as well do the following

Title enumTitle = (Title)Enum.Parse(ddl.SelectedValue); 

Upvotes: 1

Related Questions