0

I want to remove the Blank/Empty entry from my EnumDropDownListfor - have searched online and tried below links but nothing seems to work

Remove blank/empty entry at top of EnumDropDownListFor box

Remove blank entry from EnumDropDownListFor(...)?

Code in View:-

<td>
@Html.EnumDropDownListFor(model => model.Actions, new { @id = "actions", @class = "form-control" })
</td>

Code in Model:-

[Required]
    [Range(1, int.MaxValue, ErrorMessage = "Select an Action")]
    [Display(Name = "Actions")]
    public ItemTypes Actions { get; set; }

Enum in Controller:-

 public enum ItemTypes
    {
        Add = 1,
        Remove = 2
    }

Dropdown renders as below:-

enter image description here

Ram
  • 527
  • 1
  • 10
  • 26

1 Answers1

2

Sounds like your problem is the enum defined with starting index of 1:

public enum ItemTypes
{
    Add = 1,
    Remove = 2
}

Since no enumerator specified with index 0 inside above enum, the helper includes the zero index inside SelectListItem collection list, hence an empty option shown as default selected item (remember that both enum and collections use zero-based indexing, hence first item has index of zero).

Either you could define an enumerator with index 0 to set default selected value:

public enum ItemTypes
{
    Nothing = 0,
    Add = 1,
    Remove = 2
}

Or use standard DropDownListFor helper using other property defined from SelectListItem to bind enum values:

Model

public List<SelectListItem> ActionList { get; set; }

Controller

ActionList = Enum.GetNames(typeof(ItemTypes)).Select(x => new SelectListItem { Text = x, Value = x }).ToList();

View

@Html.DropDownListFor(model => model.Actions, Model.ActionList, new { @id = "actions", @class = "form-control" })

Reference:

C# Enumeration Types (MS Docs)

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61