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!
Modified from @dav_i's answer.
This is not perfect, but it is what I am using. Below is an extension to
HtmlHelper
. The extension method will look likeEnumDropDownListFor
from ASP.NET, and useDisplayAttribute
if there is any applied to the Enum value.For example:
This will create a Enum dropdown list without the the option of Active.
Below is an extension to the HtmlHelper. It is very similar to the EnumDropDownListFor extension from ASP.NET, but it sorts the SelectListItem by the item display name. It has a suggestive name: SortedEnumDropDownListFor for not conflicts with the original extension.
If you don't want to bother with the unselected item intitia, just build a overload like this:
And you are good to go. I hope it helps.
You can create the dropdown yourself by looping through the values in the enum and only include the
<option>
if it is not Pending.Here is how it should work, but as you can see, I'm not sure what you would use for the value or text of the option tag.
I was looking for the answer to this question as it relates to .NET Core MVC. Given the following code, you can limit the enums you do not want to display within the UI:
Hope this helps anyone else looking for this answer.
You could construct a drop down list: