在ASP.NET MVC 3枚举工作 [英] Working with enums in ASP.NET MVC 3

查看:216
本文介绍了在ASP.NET MVC 3枚举工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个聪明的方法来获得MVC脚手架呈现该是枚举值模特属性下拉列表框或?

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

例如:

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.

有没有内置此MVC框架/工装样的支持?目前,当我创建从模型视图的Visual Studio会忽略枚举类型的模型属性。

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?

推荐答案

Helper方法

<一个href=\"http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx\">Dropdownlist对于枚举

我在我自己的项目成功地利用这一点。

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

这篇关于在ASP.NET MVC 3枚举工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆