从下拉列表中检索选定的枚举

我将一个枚举绑定到asp.net 4.0 C#中的下拉列表

使用是:

public enum Frequency
{
    [Description("Select a frequency")]
    None,

    [Description("Every Hour/Mintues")]
    EveryHourOrMintues, 

    [Description("Previous Day Data")]
    PreviousDayData,

    [Description("Once a week")]
    OnceaWeek
}

在从下拉列表中选择一个值时,我想要返回枚举值:我这样做:

Frequency selectedFrequency;
foreach (Frequency f in Enum.GetValues(typeof(Frequency)))
{
    if (f.ToString().Equals(this.dropDownListFrequency.SelectedValue))
    {
        selectedFrequency = f;
        break;
    }
}

它正在工作,但我肯定是一个糟糕的方式,通过循环遍历枚举中的每个项目(即使枚举非常小)

我如何检索选定的枚举,如:

Frequency selectedValue = Enum.GetValues(typeof(Frequency)).Cast<Frequency>().Select(f => f.ToString().Equals(this.dropDownListFrequency.SelectedValue));

我明白上面给出的代码有铸造问题。

编辑有关更多信息,这里是我如何绑定枚举到下拉列表

var frequencies =  Enum.GetValues(typeof(Frequency)).Cast<Frequency>().Select(f => new
            {
                Text = f.ToDescriptiveTextUsingAttributes(),
                Value = f.ToString()
            });
this.dropDownListFrequency.DataSource=frequencies ;
this.dropDownListFrequency.DataTextField = "Text";
this.dropDownListFrequency.DataValueField = "Value";

ToDescriptiveTextUsingAttributes()是返回枚举的Description属性值的扩展方法


如果下拉列表的值是枚举的整数表示形式(例如0,1,2 ...),那么您可以简单地将其转换回枚举:

Frequency f = (Frequency)int.Parse(dropDownListFrequency.SelectedValue);

如果下拉列表的值是枚举的字符串表示形式(例如“None”,“EveryHourOrMintues”...),那么可以使用Enum.Parse()

Frequency f = (Frequency)Enum.Parse(
    typeof(Frequency), dropDownListFrequency.SelectedValue);

您可以扩展ListItem类以存储实际的Frequency枚举对象,并将这些专用的ListItem对象添加到dropDownListFrequency.Items 。 当你检索dropdownListFrequency.SelectedItem你可以得到选择的实际值。

class FrequencyListItem : System.Web.UI.WebControls.ListItem.ListItem {
    private Frequency _Frequency;

    public Frequency Frequency {
        get { return _Frequency }
    }

    public FrequencyListItem (Frequency f) {
        this._Frequency = f;
        this.Text = f.ToDescriptiveTextUsingAttributes();
        this.Value = f.ToString();
    }
}

由于Items属性中的所有元素都是您的专用类,因此可以轻松地按照以下方式检索枚举值:

Frequency selectedFrequency = ((FrequencyListItem )this.dropDownListFrequency.SelectedItem).Frequency;

编辑:你甚至可以使用相同的绑定模型,你有一些小的改变:

var frequencies =  Enum.GetValues(typeof(Frequency)).Cast<Frequency>().Select(f => new FrequencyListItem()
            {
                //FrequencyListItem will auto set this in the constructor for you!
                //Text = f.ToDescriptiveTextUsingAttributes(),
                //Value = f.ToString()
            });
this.dropDownListFrequency.DataSource=frequencies;
this.dropDownListFrequency.DataTextField = "Text";
this.dropDownListFrequency.DataValueField = "Value";
链接地址: http://www.djcxy.com/p/48127.html

上一篇: Retrieving selected enum from dropdown list

下一篇: ASP.NET MVC3: Object from DropdownList in Null in Controller