Exemple #1
0
        /// <summary>
        /// http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <typeparam name="TEnum"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public static MvcHtmlString EnumDropDownListFor <TModel, TEnum>(this HtmlHelper <TModel> htmlHelper, Expression <Func <TModel, TEnum> > expression)
        {
            ModelMetadata       metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            Type                enumType = GetNonNullableModelType(metadata);
            IEnumerable <TEnum> values   = Enum.GetValues(enumType).Cast <TEnum>();

            IEnumerable <SelectListItem> items =
                from value in values
                select new SelectListItem
            {
                Text     = EnumExtension.GetDisplay(value),
                Value    = value.ToString(),
                Selected = value.Equals(metadata.Model)
            };

            if (metadata.IsNullableValueType)
            {
                items = new[] { new SelectListItem {
                                    Text = "", Value = ""
                                } }.Concat(items);
            }

            return(htmlHelper.DropDownListFor(
                       expression,
                       items
                       ));
        }
Exemple #2
0
        public static MvcHtmlString DisplayForEnum <TEnum>(this HtmlHelper htmlHelper, TEnum value)
        {
            var text = EnumExtension.GetDisplay <TEnum>(value);

            return(new MvcHtmlString(text));
        }