MVC - change the default text in the drop-down menu

I have a view model containing enum:

public class PasswordChangerIndexViewModel
{
    public enum DatabaseTypes
    {
        Main = 10,
        Florida = 20,
        Illinois = 30,
        Missouri = 40,
        NewHampshire = 50,
        NewJersey = 60,
        Oklahome = 70
    };

    [DisplayName("Database")]
    public DatabaseTypes DatabaseType { get; set; }

}

And, in my opinion, I use EnumDropDownListForto create a drop down list:

<div class="row">
    <div class="col-md-1">
        <div class="form-group">
            @Html.EnumDropDownListFor(z => z.DatabaseType, "** Select a Database **");
        </div>
    </div>
</div>

This works, but I wonder if there is a way to change the text. I want to New Hampshiredisplay instead NewHampshireand New Jerseyinstead NewJersey. Is there a DisplayName attribute or something that I can apply to my view model to fix this?

+4
source share
2 answers

Use DisplayAttributelistings for your members:

public enum DatabaseTypes
{
  Main = 10,
  Florida = 20,
  Illinois = 30,
  Missouri = 40,
  [Display(Name = "New Hampshire")]
  NewHampshire = 50,
  [Display(Name = "New Jersey")]
  NewJersey = 60,
  Oklahome = 70
};

In general, you should use [Display]instead [DisplayName], as it supports localization.

+2

Enum DropdownList. , , :

Views/Shared/EditorTemplates EnumDropdown.cshtml

@model Enum

@{
    var sort = (bool?)ViewData["sort"] ?? false;
    var enumValues = new List<object>();
    foreach (var val in Enum.GetValues(Model.GetType()))
    {
        enumValues.Add(val);
    }
}

@Html.DropDownListFor(m => m,
    enumValues
    .Select(m =>
    {
        string enumVal = Enum.GetName(Model.GetType(), m);
        var display = m.GetDescription() ?? enumVal;
        return new SelectListItem()
        {
            Selected = (Model.ToString() == enumVal),
            Text = display,
            Value = enumVal
        };
    })
    .OrderBy(x => sort ? x.Text : null)
    ,new { @class = "form-control" })

GetDescription():

    public static string GetDescription(this object enumerationValue)
    {
        Type type = enumerationValue.GetType();
        if (!type.IsEnum)
            throw new ArgumentException("EnumerationValue must be of Enum type", "enumerationValue");

        //Tries to find a DescriptionAttribute for a potential friendly name
        //for the enum
        MemberInfo[] memberInfo = type.GetMember(enumerationValue.ToString());
        if (memberInfo != null && memberInfo.Length > 0)
        {
            object[] attrs = memberInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

            if (attrs != null && attrs.Length > 0)
            {
                //Pull out the description value
                return ((DescriptionAttribute)attrs[0]).Description;
            }
        }
        //If we have no description attribute, just return the ToString of the enum
        return enumerationValue.ToString();

    }

. :

public enum MyEnum 
{
    [Description("The First Option1")]
    Option1,
    Option2
}
public class MyModel
{
    [UIHint("EnumDropdown")] //matches EnumDropdown.cshtml
    public MyEnum TheEnum { get; set; }
}

@model MyModel
@Html.EditorFor(x => x.TheEnum)

" " "2"

+1

All Articles