Exclude/Remove Value from MVC 5.1 EnumDropDownListFor

前端 未结 5 1753
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 06:01

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 h

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 06:46

    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 like EnumDropDownListFor from ASP.NET, and use DisplayAttribute if there is any applied to the Enum value.

    /// 
    /// Returns an HTML select element for each value in the enumeration that is
    /// represented by the specified expression and predicate.
    /// 
    /// The type of the model.
    /// The type of the value.
    /// The HTML helper instance that this method extends.
    /// An expression that identifies the object that contains the properties to display.
    /// The text for a default empty item. This parameter can be null.
    /// A  to filter the items in the enums.
    /// An object that contains the HTML attributes to set for the element.
    /// An HTML select element for each value in the enumeration that is represented by the expression and the predicate.
    /// If expression is null.
    /// If TEnum is not Enum Type.
    public static MvcHtmlString EnumDropDownListFor(this HtmlHelper htmlHelper, Expression> expression, Func predicate, string optionLabel, object htmlAttributes) where TEnum : struct, IConvertible
    {
        if (expression == null)
        {
            throw new ArgumentNullException("expression");
        }
    
        if (!typeof(TEnum).IsEnum)
        {
            throw new ArgumentException("TEnum");
        }
    
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        IList selectList = Enum.GetValues(typeof(TEnum))
                .Cast()
                .Where(e => predicate(e))
                .Select(e => new SelectListItem
                    {
                        Value = Convert.ToUInt64(e).ToString(),
                        Text = ((Enum)(object)e).GetDisplayName(),
                    }).ToList();
        if (!string.IsNullOrEmpty(optionLabel)) {
            selectList.Insert(0, new SelectListItem {
                Text = optionLabel,
            });
        }
    
        return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
    }
    
    /// 
    /// Gets the name in  of the Enum.
    /// 
    /// A  that the method is extended to.
    /// A name string in the  of the Enum.
    public static string GetDisplayName(this Enum enumeration)
    {
        Type enumType = enumeration.GetType();
        string enumName = Enum.GetName(enumType, enumeration);
        string displayName = enumName;
        try
        {
            MemberInfo member = enumType.GetMember(enumName)[0];
    
            object[] attributes = member.GetCustomAttributes(typeof(DisplayAttribute), false);
            DisplayAttribute attribute = (DisplayAttribute)attributes[0];
            displayName = attribute.Name;
    
            if (attribute.ResourceType != null)
        {
                displayName = attribute.GetName();
            }
        }
        catch { }
        return displayName;
    }
    

    For example:

    @Html.EnumDropDownListFor(
        model => model.UserStatus,
        (userStatus) => { return userStatus != UserStatus.Active; },
        null,
        htmlAttributes: new { @class = "form-control" });
    

    This will create a Enum dropdown list without the the option of Active.

提交回复
热议问题