8

In my ViewModel, I have a property that creates an enumeration for my form's drop down menu.

public enum Colors
    {
    [Description("Dark Red")]
    DarkRed = 0,
    [Description("Orange")]
    Orange = 1,
    [Description("Blue")]
    Blue = 2
    }

My Helper returns:

<select id="ddlColor">
    <option value="DarkRed">Dark Red</option>
    <option value="Orange">Orange</option>
    <option value="Blue">Blue</option>
</select>

However, when I call the property in my model, I only get the name and not the value, e.g. DarkRed and not 0.

model.Selections = InsertForm(model.Color);

How can I cast this in my model reference so I get the value from the enum?

mmcglynn
  • 7,668
  • 16
  • 52
  • 76
  • I would look at this one looks like they had similar issue http://stackoverflow.com/questions/943398/get-int-value-from-enum – Ryan Schlueter Sep 19 '13 at 13:47

2 Answers2

8

You may have to cast the value like this:-

var value = (int)model.Color;

NOTE:-

All enumeration type have an underlying type, which can be any integral type except char.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0

You could easily cast it to an int.

By default enums are Int32.

so you could say

var value = (int)model.Color;

Since you are using asp.net mvc, i'm going to assume that model.Selections is a List<SelectListItem>.

See below.

  public List<SelectListItem> GetList<TEnum>() where TEnum : struct
        {
            var items = new List<SelectListItem>();
            foreach (int value in Enum.GetValues(typeof(TEnum)))
            {
                items.Add(new SelectListItem
                {
                    Text = Enum.GetName(typeof(TEnum), value),
                    Value = value
                });
            } 
            return items;


        }

You can now say model.Selections = GetList<Color>();

scartag
  • 17,548
  • 3
  • 48
  • 52