with mvc example enumdropdownlistfor enum dropdownlist c# asp.net-mvc razor enums html-helper

c# - with - enumdropdownlistfor mvc 5 example



Excluir/eliminar valor de MVC 5.1 EnumDropDownListFor (4)

Tengo una lista de enumeraciones que estoy usando para una página de administración de usuarios. Estoy usando el nuevo HtmlHelper en MVC 5.1 que me permite crear una lista desplegable para valores Enum. Ahora tengo la necesidad de eliminar el valor Pendiente de la lista, este valor solo se establecerá programáticamente y el usuario nunca debe configurarlo.

Enum:

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

Ver:

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

¿Hay alguna forma de reemplazar el control actual o escribir un HtmlHelper personalizado que me permita especificar una enumeración o enumeraciones para excluir de la lista resultante? ¿O sugeriría que haga algo del lado del cliente con jQuery para eliminar el valor de la lista desplegable una vez que se ha generado?

¡Gracias!


A continuación se encuentra una extensión de HtmlHelper. Es muy similar a la extensión EnumDropDownListFor de ASP.NET, pero clasifica el SelectListItem por el nombre para mostrar del elemento. Tiene un nombre sugestivo: SortedEnumDropDownListFor para que no entre en conflicto con la extensión original.

/// <summary> /// /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TEnum">The type of the value.</typeparam> /// <param name="htmlHelper">The HTML helper instance that this method extends.</param> /// <param name="expression">An expression that identifies the object that contains the properties to display</param> /// <param name="initalValue">The unselected item initial value</param> /// <param name="htmlAttributes"></param> /// <returns></returns> public static MvcHtmlString SortedEnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, string initalValue, object htmlAttributes = null) { ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData); Type enumType = GetNonNullableModelType(metadata); Type baseEnumType = Enum.GetUnderlyingType(enumType); List<SelectListItem> items = new List<SelectListItem>(); foreach (FieldInfo field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public)) { string text = field.Name; string value = Convert.ChangeType(field.GetValue(null), baseEnumType).ToString(); bool selected = field.GetValue(null).Equals(metadata.Model); foreach (DisplayAttribute displayAttribute in field.GetCustomAttributes(true).OfType<DisplayAttribute>()) { text = displayAttribute.GetName(); } items.Add(new SelectListItem { Text = text, Value = value, Selected = selected }); } items = new List<SelectListItem>(items.OrderBy(s => s.Text)); items.Insert(0, new SelectListItem { Text = initalValue, Value = "" }); return htmlHelper.DropDownListFor(expression, items, htmlAttributes); } private static Type GetNonNullableModelType(ModelMetadata modelMetadata) { Type realModelType = modelMetadata.ModelType; Type underlyingType = Nullable.GetUnderlyingType(realModelType); if (underlyingType != null) { realModelType = underlyingType; } return realModelType; }

Si no quiere molestarse con la ítem de ítem no seleccionado, solo cree una sobrecarga como esta:

public static MvcHtmlString SortedEnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes = null) { MvcHtmlString helper = SortedEnumDropDownListFor(htmlHelper, expression, string.Empty, htmlAttributes); return helper; }

Y eres bueno para ir. Espero que ayude.


Modificado de la respuesta de @ dav_i.

Esto no es perfecto, pero es lo que estoy usando. A continuación se encuentra una extensión de HtmlHelper . El método de extensión se verá como EnumDropDownListFor de ASP.NET y usar DisplayAttribute si hay alguno aplicado al valor de Enum.

/// <summary> /// Returns an HTML select element for each value in the enumeration that is /// represented by the specified expression and predicate. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TEnum">The type of the value.</typeparam> /// <param name="htmlHelper">The HTML helper instance that this method extends.</param> /// <param name="expression">An expression that identifies the object that contains the properties to display.</param> /// <param name="optionLabel">The text for a default empty item. This parameter can be null.</param> /// <param name="predicate">A <see cref="Func{TEnum, bool}"/> to filter the items in the enums.</param> /// <param name="htmlAttributes">An object that contains the HTML attributes to set for the element.</param> /// <returns>An HTML select element for each value in the enumeration that is represented by the expression and the predicate.</returns> /// <exception cref="ArgumentNullException">If expression is null.</exception> /// <exception cref="ArgumentException">If TEnum is not Enum Type.</exception> public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, Func<TEnum, bool> 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<SelectListItem> selectList = Enum.GetValues(typeof(TEnum)) .Cast<TEnum>() .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); } /// <summary> /// Gets the name in <see cref="DisplayAttribute"/> of the Enum. /// </summary> /// <param name="enumeration">A <see cref="Enum"/> that the method is extended to.</param> /// <returns>A name string in the <see cref="DisplayAttribute"/> of the Enum.</returns> 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; }

Por ejemplo:

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

Esto creará una lista desplegable Enum sin la opción de Activo.


Puede construir una lista desplegable:

@{ // 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)


Puede crear el menú desplegable usted mismo al recorrer los valores en la enumeración y solo incluir la <option> si no está Pendiente.

Así es cómo debería funcionar, pero como puede ver, no estoy seguro de qué usaría para el valor o el texto de la etiqueta de opción.

<select> foreach (var status in Enum.GetValues(typeof(UserStatus))) { if(status != UserStatus.Pending) { <option value="status.???">@status.???</option> } } </select>