Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding an Enum to LINQ and SelectListItem

I'm trying to bind the following enum

public enum CertificateTypes : byte
{
    None = 0,
    Original = 1,
    AuthenticatedCopy = 2,
    Numbered = 3
}

to a tinyint column on the database. However, when creating the SelectListItems and calling, for instance, Person.CertificateTypes.Original.ToString() I get this:

<option value="Original">Original</option>

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? Or is there a way to make this work "automagically"?

like image 330
changelog Avatar asked Dec 06 '22 07:12

changelog


2 Answers

If you want automagically you can use

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

Problem here is you're only going to get the bytes, so you would probably need to select a new type something like...

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

That would just take possible values from the enum and translate it into an IEnumerable of CertificateTypes then taking each value and translating it into a new KeyValuePair.

One thing to note, it's usually a good idea to only make your enums pluralized if you have a [Flags] attribute on them. Otherwise I would name it singular.

Gotta love LINQ!

like image 78
Chad Moran Avatar answered Dec 07 '22 20:12

Chad Moran


Not sure how the following translates to a SelectListItems in ASP.NET/MVC, though, as I have no experience, but maybe this can be of use.


Of course you have to specifically cast the enum to it's underlying type like (byte)Person.CertificateTypes.Original to get it to talk to the database nicely.

In WinForms, I use an IList of KeyValuePair<byte,string> to bind to a ComboBox, using something like the following:

foreach (Enum value in Enum.GetValues(typeof(CertificateTypes))
    MyBindingIList.Add(new KeyValuePair<byte,string>((byte)value, value.ToString()));

I then bind the ComboBox and set it's DisplayMember to "Value" and ValueMember to "Key". (You can switch the Key and Value in the KeyValuePair to whatever makes sense for you. For me, the key comes out of the database, so it makes sense to be the numeric type.)

like image 43
lc. Avatar answered Dec 07 '22 19:12

lc.