Search code examples
c#asp.net-mvcrazorenumshtml-helper

Exclude/Remove Value from MVC 5.1 EnumDropDownListFor


I have a list of enums that I am using for a user management page. I'm using the new HtmlHelper in MVC 5.1 that allows me to create a dropdown list for Enum values. I now have a need to remove the Pending value from the list, this value will only ever be set programatically and should never be set by the user.

Enum:

public enum UserStatus
{
    Pending = 0,
    Limited = 1,
    Active = 2
}

View:

@Html.EnumDropDownListFor(model => model.Status)

Is there anyway, either overriding the current control, or writing a custom HtmlHelper that would allow me to specify an enum, or enums to exclude from the resulting list? Or would you suggest I do something client side with jQuery to remove the value from the dropdown list once it has been generated?

Thanks!


Solution

  • You could construct a drop down list:

    @{ // you can put the following in a back-end method and pass through ViewBag
       var selectList = Enum.GetValues(typeof(UserStatus))
                            .Cast<UserStatus>()
                            .Where(e => e != UserStatus.Pending)
                            .Select(e => new SelectListItem 
                                { 
                                    Value = ((int)e).ToString(),
                                    Text = e.ToString()
                                });
    }
    @Html.DropDownListFor(m => m.Status, selectList)