我如何填充枚举值一个DropDownList? [英] How do I populate a dropdownlist with enum values?

查看:126
本文介绍了我如何填充枚举值一个DropDownList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的视图模型的属性之一枚举。我想显示包含枚举的所有值的下拉列表。我能得到这个具有以下code工作。

我想知道是是否存在由枚举转换为一个IEnumerable一个简单的方法?我可以做手工,如下面的例子,但是当我添加一个新的枚举值code休息。我想,我可以通过反射做到按本<一个href=\"http://devlicio.us/blogs/joe_niland/archive/2006/10/10/Generic-Enum-to-List_3C00_T_3E00_-converter.aspx\">example,但却有其他的方法可以做到这一点?

 公开枚举货币
{
  CAD,USD,EUR
}公共视图模型
{
  [需要]
  公共货币SelectedCurrency {搞定;组;}  公众的SelectList货币
  {
    清单&LT;货币和GT; C =新的List&LT;货币和GT;();
    c.Add(Currencies.CAD);
    c.Add(Currencies.USD);
    c.Add(流通货币);    返回新的SelectList(C);
  }
}


解决方案

我使用的是帮手,我发现<一个href=\"http://blog.thomasbandt.de/39/2316/de/blog/aspnet-mvc-2-enumeration-dropdownlist-localization.html\"相对=nofollow>此处填充我SelectLists与通用枚举类型,我做了一点修改,虽然添加选定的价值,这里是它的样子:

 公共静态的SelectList ToSelectList&LT; T&GT;(这件T枚举,串选择)
{
    无功源= Enum.GetValues​​(typeof运算(T));    VAR项目=新的解释和LT;对象,字符串&GT;();    VAR displayAttributeType = typeof运算(DisplayAttribute);    的foreach(源VAR值)
    {
        字段信息字段= value.GetType()getfield命令(value.ToString())。        DisplayAttribute ATTRS =(DisplayAttribute)字段。
                      GetCustomAttributes(displayAttributeType,FALSE).FirstOrDefault()        items.Add(值,ATTRS = NULL attrs.GetName():!?value.ToString());
    }    返回新的SelectList(项目,键,值,选择);
}

关于它的好处是,它会读取DisplayAttribute作为标题,而不是枚举名称。 (如果您的枚举包含空格,或者您需要本地化那么它会让你的生活变得更轻松)

所以,你需要将显示attirubete添加到您的枚举是这样的:

 公开枚举User_Status
{
    [显示(NAME =等待激活)]
    之前,//用户帐户被挂起。可以登录/不能参加    [显示(NAME =激活)]
    活跃​​,//用户帐户被激活。可以登录    [显示(名称=已禁用)
    残疾人,//用户帐户Diabled。无法登录
}

和你这是怎么在你的意见中使用它们。

 &LT;%:Html.DropDownList(ChangeStatus,ListExtensions.ToSelectList(Model.statusType,user.Status))%GT;

Model.statusType 只是一个类型 User_Status 的枚举对象。

这就是它,在你的ViewModels没有更多SelectLists。在我的例子,我在refrencing我的ViewModel一个枚举,但你可以Refrence枚举在您看来,虽然直接输入。我只是在做它使一切干净,漂亮。

希望那是有益的。

I have an enum for one of the properties of my view-model. I want to display a drop-down list that contains all the values of the enum. I can get this to work with the following code.

What I'm wondering is whether there is a simple way to convert from an enum to an IEnumerable? I can do it manually as in the following example, but when I add a new enum value the code breaks. I imagine that I can do it via reflection as per this example, but but are there other ways to do this?

public enum Currencies
{
  CAD, USD, EUR
}

public ViewModel
{
  [Required]
  public Currencies SelectedCurrency {get; set;}

  public SelectList Currencies
  {
    List<Currencies> c = new List<Currencies>();
    c.Add(Currencies.CAD);
    c.Add(Currencies.USD);
    c.Add(Currencies.EUR);

    return new SelectList(c);
  }
}

解决方案

I'm using a helper that i found here to populate my SelectLists with a generic enum type, i did a little modification to add the selected value though, here's how it looks like :

public static SelectList ToSelectList<T>(this T enumeration, string selected)
{
    var source = Enum.GetValues(typeof(T));

    var items = new Dictionary<object, string>();

    var displayAttributeType = typeof(DisplayAttribute);

    foreach (var value in source)
    {
        FieldInfo field = value.GetType().GetField(value.ToString());

        DisplayAttribute attrs = (DisplayAttribute)field.
                      GetCustomAttributes(displayAttributeType, false).FirstOrDefault()

        items.Add(value, attrs != null ? attrs.GetName() : value.ToString());
    }

    return new SelectList(items, "Key", "Value", selected);
}

The nice thing about it is that it reads the DisplayAttribute as the title rather than the enum name. (if your enums contain spaces or you need localization then it makes your life much easier)

So you will need to add the Display attirubete to your enums like this :

public enum User_Status
{
    [Display(Name = "Waiting Activation")]
    Pending,    // User Account Is Pending. Can Login / Can't participate

    [Display(Name = "Activated" )]
    Active,                // User Account Is Active. Can Logon

    [Display(Name = "Disabled" )]
    Disabled,          // User Account Is Diabled. Can't Login
}

and this is how you use them in your views.

<%: Html.DropDownList("ChangeStatus" , ListExtensions.ToSelectList(Model.statusType, user.Status))%>

Model.statusType is just an enum object of type User_Status.

That's it , no more SelectLists in your ViewModels. In my example I'm refrencing an enum in my ViewModel but you can Refrence the enum type directly in your view though. I'm just doing it to make everything clean and nice.

Hope that was helpful.

这篇关于我如何填充枚举值一个DropDownList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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