views:

156

answers:

2

Hi all,

I render a dropdown list to allow the user to select the enum value using this solution http://blogs.msdn.com/b/ukadc/archive/2010/06/22/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx.

this is the helper

public static MvcHtmlString EnumDropDownListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TEnum>> expression, object htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
        IEnumerable<TEnum> values = Enum.GetValues(typeof(TEnum)).Cast<TEnum>();

        IEnumerable<SelectListItem> items =
            values.Select(value => new SelectListItem
            {
                Text = CultureLocalizationHelper.GetString(value.ToString(), typeof(SiteResources.Core.Views.CulturalConfiguration.Index)),
                Value = value.ToString(),
                Selected = value.Equals(metadata.Model)
            });

        return htmlHelper.DropDownListFor(expression, items, htmlAttributes);
    }

This approach works very well with any enum but not with this

public enum Color
{

    Orange = 1,

    Green = 2,

    Blue = 3,

    Primary = 4
}

I have a very weird problem, the helper does not work with this enum.

I debug the SelectListItems and there's one that is selected but DropDownListFor does not render any of the elements with selected="selected"

Any idea?

Thanks for your time!

A: 

One way to to overload an Enum ToString() and/or create your own Attribute as described in http://lostinloc.com/2008/05/06/c-overloading-an-enums-tostring/.

Erik Philips
A: 

specify a new SelectList(values, selectedValue) instead of specifying the SelectListItems directly to set the selected value

<%: Html.DropDownListFor(model=> model.Type, new SelectList(Enum.GetValues(typeof(UserType)), (Model??new User()).Type)) %>
Gregg