Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get an enum value from my ASP.NET MVC property?

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?

like image 623
mmcglynn Avatar asked Sep 19 '13 13:09

mmcglynn


1 Answers

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.

like image 63
Rahul Tripathi Avatar answered Nov 21 '22 04:11

Rahul Tripathi