Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 400
James Avatar asked Mar 22 '16 15:03

James


2 Answers

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?

like image 196
Cloud SME Avatar answered Nov 17 '22 20:11

Cloud SME


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"  })
like image 26
Gulnar Agayeva Avatar answered Nov 17 '22 20:11

Gulnar Agayeva