James
James

Reputation: 1501

Remove blank/empty entry at top of EnumDropDownListFor box

I am rendering a drop down list box using my enums and I only have 3 options, but for some reason it is displaying four. The top and default option is simply blank/empty and I want this removed. I want the top/default value to be 'Option1'.

Enums:

public enum EventType
{
    [Display(Name = "Option 1")]
    Option1,

    [Display(Name = "Option 2")]
    Option2,

    [Display(Name = "Option 3")]
    Option3
}

View:

@Html.EnumDropDownListFor(model => model.EventType, null, new { @id = "eventType", @class = "form-control" })

Thanks for your help.

Upvotes: 10

Views: 8660

Answers (3)

Gulnar Agayeva
Gulnar Agayeva

Reputation: 21

I also had the same problem.Solved this starting enum from 0 not 1 .

public enum EventType
{
[Display(Name = "Option 1")]
Option1,

[Display(Name = "Option 2")]
Option2,

[Display(Name = "Option 3")]
Option3
}

@Html.EnumDropDownListFor(model => model.EventType,      
              new {@id = "eventType", @class = "form-control"  })

Upvotes: 2

ThunD3eR
ThunD3eR

Reputation: 3456

I spent some time getting the above to work and was unsuccessful.

I found an alternative way :

HTML:

@Html.DropDownList("types",
               Helper.Gettypes(),
               new { @class = "form-control", @title = "---  Choose  ---" })

Code:

    public static List<SelectListItem> Gettypes()
    {
        var enums = Enum.GetNames(typeof(WorkLogType)).ToList();

        var selectLIst = enums.Select(x => new SelectListItem {Value = x, Text = x}).ToList();

        return selectLIst;
    }

Upvotes: 0

Andy T
Andy T

Reputation: 9881

Your second parameter is the "Option Label" which is used to set the first item in the dropdown. From the documentation: "The text for a default empty item"

Use an overload that doesn't take in the option label:

@Html.EnumDropDownListFor(model => model.EventType, new { @id = "eventType", @class = "form-control" })

UPDATE

I just tried your code. When I do both:

@Html.EnumDropDownListFor(model => model.EventType, null, new { @id = "eventType", @class = "form-control" })

And

@Html.EnumDropDownListFor(model => model.EventType, new { @id = "eventType", @class = "form-control" })

I get:

enter image description here

The only time I get another option in the dropdown is when I pass in a string as the second parameter, such as "Select..."

Any chance you are doing something with javascript to add an item to the dropdown?

Upvotes: 13

Related Questions