将枚举绑定到LINQ和SelectListItem

cha*_*log 4 c# linq forms asp.net-mvc

我正在尝试绑定以下枚举

public enum CertificateTypes : byte
{
    None = 0,
    Original = 1,
    AuthenticatedCopy = 2,
    Numbered = 3
}
Run Code Online (Sandbox Code Playgroud)

tinyint数据库的一列.但是,在创建SelectListItems并调用时,例如,Person.CertificateTypes.Original.ToString() I get this:

<option value="Original">Original</option>
Run Code Online (Sandbox Code Playgroud)

which is not bindable to a byte? column. How should I do this? Should I explicitly set the value to "1" on the Value

tinyint

Person.CertificateTypes.Original.ToString() I get this:

public enum CertificateTypes : byte
{
    None = 0,
    Original = 1,
    AuthenticatedCopy = 2,
    Numbered = 3
}
Run Code Online (Sandbox Code Playgroud)

which is not bindable to a byte? column. How should I do this? Should I explicitly set the value to "1" on the Value property of the SelectListItem?或者有没有办法让这项工作"自动化"?

Cha*_*ran 15

如果你想自动化,你可以使用

var enumValues = Enum.GetValues(typeof(CertificateTypes)).Cast<CertificateTypes>().Select(e => (byte)e);
var selectList = new SelectList(enumValues);
Run Code Online (Sandbox Code Playgroud)

这里的问题是你只是要获取字节,所以你可能需要选择一个像......这样的新类型.

var enumValues = Enum.GetValues(typeof(CertificateTypes)).Cast<CertificateTypes>()
                                                         .Select(e => new KeyValuePair<byte, string>((byte)e, e.ToString()));
var selectList = new SelectList(enumValues, "Key", "Value");
Run Code Online (Sandbox Code Playgroud)

这将从枚举中获取可能的值,并将其转换为IEnumerable of CertificateTypes,然后获取每个值并将其转换为新的KeyValuePair.

有一点需要注意,如果你的枚举属性为[Flags]属性,那么通常最好只让你的枚举复数化.否则我会把它命名为奇异.

一定要爱LINQ!