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"?

By : changelog


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!

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.)

By : lc.

I really doubt that calling ToString() on an enum returns xml... can you clarify what is happening? You probably want to either cast the enum to an byte/int (and work in terms of numbers much of the time), or use Enum.Parse at some point - but it is hard to say without understanding how you have got it hooked together...

This video can help you solving your question :)
By: admin