Working with enums in ASP.NET MVC 3

独自空忆成欢 提交于 2019-12-22 02:21:04

问题


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?


回答1:


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



回答2:


Great solution here: How do you create a dropdownlist from an enum in ASP.NET MVC?

That's for the drop-down, obviously, but for the other UI options you want you can use the collection of values to create them via loops.

Not built in, but pretty easy to do.



来源:https://stackoverflow.com/questions/6133771/working-with-enums-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!