2

I want to populate a dropdown list with gender values using enum in MVC, but Enum.GetValues(typeof(...) is not returning values. Here is .cshtml part:

    <div class="form-group">
        @Html.LabelFor(m => m.parGender, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.parGender, new SelectList(Enum.GetValues(typeof(Gender))), new { @class = "form-control" })
        </div>
    </div>

And here is the Model for this one:

        [Required(ErrorMessage = "Select your gender!")]
        [Display(Name = "Gender:")]
        public Gender parGender { get; set; }

        public enum Gender
        {
            Male,
            Female
        }

What did I miss for this to work?

hasanovs
  • 33
  • 2

2 Answers2

0

You need to cast the result to the actual array type you want

(Gender[])Enum.GetValues(typeof(Gender))
vsarunov
  • 1,433
  • 14
  • 26
0

You will have to cast it and then possibly select the right type - I have used this for Kendo Dropdowns, not sure if it will be exactly the same:

Enum.GetValues(typeof(Gender)).Cast<Gender>().Select(at =>
    new SelectListItem
    {
        Text = at.ToString(),
        Value = ((int)at).ToString()
    }
))
andyb952
  • 1,931
  • 11
  • 25