如何使用枚举值填充下拉列表? [英] How do I populate a dropdownlist with enum values?

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

问题描述

我有一个我的视图模型的属性的枚举。我想显示一个包含枚举的所有值的下拉列表。我可以使用以下代码:



我想知道是否有一种简单的方式将枚举转换为IEnumerable?我可以像下面的例子那样手动执行,但是当我添加一个新的枚举值时,代码就会中断。我想我可以通过反思来做到这一点,这个示例,但是还有其他方法可以做到吗?

  public enum货币
{
CAD,USD,EUR
}

public ViewModel
{
[必需]
public货币SelectedCurrency {get; set;}

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

返回新的SelectList(c);
}
}


解决方案

'使用一个帮助者,我发现这里使用通用枚举类型填充我的选择列表,我做了一些修改,以添加所选值,以下是它的外观:

  public static SelectList ToSelectList< T>(此T枚举,选择字符串)
{
var source = Enum.GetValues(typeof(T));

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

var displayAttributeType = typeof(DisplayAttribute);

foreach(来源中的var值)
{
FieldInfo field = value.GetType()GetField(value.ToString());

DisplayAttribute attrs =(DisplayAttribute)字段。
GetCustomAttributes(displayAttributeType,false).FirstOrDefault()

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

返回新的SelectList(项目,Key,Value,选择);
}

很棒的是它将DisplayAttribute读取为标题,而不是枚举名称。 (如果您的枚举包含空格或需要本地化,那么这样会使您的生活更加容易)



所以,您需要将Display attirubete添加到您的枚举中: p>

  public enum User_Status 
{
[显示(Name =等待激活)]
待定,//用户帐户挂起。可以登录/不能参与

[显示(名称=激活)]
活动,//用户帐户活动。可以登录

[显示(名称=禁用)]
已禁用,//用户帐户已被清除。无法登录
}

这是您在视图中使用它们的方式。 / p>

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

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



就是这样,ViewModels中没有更多的SelectLists。在我的例子中,我在我的ViewModel中重新枚举一个枚举,但是你可以直接在你的视图中引用枚举类型。我只是为了使一切都清洁和美好。



希望这是有帮助的。


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.

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

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