The extension method EnumDropDownListFor has an extra parameter to filter enum-values in a dropdownlist in an asp.net razor form.
Example:
<div>
@Html.EnumDropDownListFor(
model => model.Category,
(category => (category != Category.Books)),
new { @class = "form-control" })
</div>
namespace HtmlHelper.Extensions
{
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;
public static class SelectExtension
{
public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TEnum>> expression, Func<TEnum, bool> filter, object htmlAttributes) where TEnum : IConvertible
{
if (expression == null)
{
throw new ArgumentNullException("expression");
}
if (!typeof(TEnum).IsEnum)
{
throw new ArgumentException("TEnum");
}
var selectList = Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Where(e => filter(e))
.Select(e => new SelectListItem
{
Value = e.ToUInt64(null).ToString(),
Text = e.ToString(),
});
return htmlHelper.DropDownListFor(expression, selectList, htmlAttributes);
}
}
}
Kommentare zum Snippet