I want to fill a selector using an enumerator. I want to do this operation in theView page with razor/VB or C#
            Asked
            
        
        
            Active
            
        
            Viewed 653 times
        
    2 Answers
1
            
            
        If you have an enum something like below then you may prefer to split the names at capital letters.
public enum Gender
{
    NotSpecified = 0,
    Male,
    Female
}
Here is the code to split and return the SelectList to show the enums in the UI but get the selected value back as enum in model.
Splitting logic is from one of the SO post. Thanks to the poster.
public class EnumHelper
{
    public static SelectList GetSelectList<T>()
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
            throw new ArgumentException("The specified type is not enum");
        List<SelectListItem> items = new List<SelectListItem>();
        var values = Enum.GetValues(enumType);
        foreach (var value in values)
        {
            items.Add(new SelectListItem()
            {
                Value = value.ToString(),
                // Split at capital letters
                Text = Regex.Replace(Enum.GetName(enumType, value), "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 ")
            });
        }
        return new SelectList(items, "Value", "Text");
    }
A sample usage in razor is below
<div class="editor-label">
    @Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Gender, EnumHelper.GetSelectList<Gender>())
    @Html.ValidationMessageFor(model => model.Gender)
</div>
HTH
 
    
    
        Community
        
- 1
- 1
 
    
    
        Anil Vangari
        
- 570
- 7
- 12
0
            For simple enum names the following code should work.
In Razor/C#
<tr>
    <th>
        <div class="editor-label">
            @Html.LabelFor(model => model.Gender)
        </div>
    </th>
    <td>
        <div class="editor-field">
            @Html.DropDownListFor(model => model.Gender, new SelectList(Enum.GetValues(typeof(Gender))))
            @Html.ValidationMessageFor(model => model.Gender)
        </div>
    </td>
</tr>
My enum is simple one like this
public enum Gender
{
    Male,
    Female
}
 
    
    
        Anil Vangari
        
- 570
- 7
- 12
 
    