Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with enums in ASP.NET MVC 3

Is there a clever way to get the MVC scaffolding to render a dropdown or listbox for model properties that are enum values?

Example:

public class MyModel
{
    public Color MyColor { get; set; }
    public Option Options { get; set; }
}

public enum Color
{ 
    None = 0,
    Red = 1,
    Blue = 2, 
    White = 3
}

[Flags]
public enum Option
{ 
    NotSet = 0,
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Option4 = 8
}

For the “Color” property, a dropdown would be nice. And for the “Options” property, a combo box or list of checkboxes would be cool.

Is there any kind of support built into the MVC framework/tooling for this? Currently, Visual Studio just ignores the model properties of enum types when I create a View from the model.

What would be the best way to implement this?

like image 510
Jakob Gade Avatar asked May 26 '11 04:05

Jakob Gade


1 Answers

Helper method

Dropdownlist for Enum

I've utilized this successfully in my own projects.

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>();

    TypeConverter converter = TypeDescriptor.GetConverter(enumType);

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

    if (metadata.IsNullableValueType)
    {
        items = SingleEmptyItem.Concat(items);
    }

    return htmlHelper.DropDownListFor(
        expression,
        items
        );
}
like image 158
Khepri Avatar answered Sep 25 '22 12:09

Khepri