2

I'm new to ASP.NET MVC 3. I'm trying to display some options in a drop down list. The options will mimic values in an enum. The enum has the following three values:

public enum Gender 
{
  Male = 0,
  Female = 1,
  NotSpecified=-1
}

I am trying to generate the following HTML

<select>
  <option value="0">Male</option>
  <option value="1">Female</option>
  <option value="2">Not Specified</option>
</select>

I'm trying to do this with Razor, but i'm a bit lost. Currently I have:

@Html.DropDownList("relationshipDropDownList", WHAT GOES HERE?)

Please note, I cannot edit the enum. Thank you for your help!

Phone Developer
  • 1,411
  • 4
  • 25
  • 36

4 Answers4

1

something like this...

//add this to your view model
IEnumerable<SelectListItem> genders = Enum.GetValues(typeof(Gender))
    .Cast<Gender>()
    .Select(x => new SelectListItem
    {
        Text = x.ToString(),
        Value = x.ToString()
    }); 

@Html.DropDownList("relationshipDropDownList", Model.genders)
dotjoe
  • 26,242
  • 5
  • 63
  • 77
0
    public enum EnumGender
    {
        Male = 0,
        Female = 1,
        NotSpecified = -1
    }


@Html.DropDownList("relationshipDropDownList", (from EnumGender e in Enum.GetValues(typeof(EnumGender))
                                                               select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), "select", new { @style = "" })



//or

@Html.DropDownList("relationshipDropDownList", (from EnumGender e in Enum.GetValues(typeof(EnumGender))
                                                               select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), null, new { @style = "" })
Thulasiram
  • 8,432
  • 8
  • 46
  • 54
0

There is an answer to the same question here

The accepted answer has an extension method to convert the enum into a selectlist, which can be used like this

In the controller

ViewBag.Relationships = Gender.ToSelectList();

in the partial

@Html.DropDownList("relationshipDropDownList", ViewBag.Relationships)
Community
  • 1
  • 1
Dallas
  • 2,217
  • 1
  • 13
  • 13
0
@Html.DropDownList("relationshipDropDownList", Model.GenderSelectList);

However, I would rather use DropDownListFor to avoid using magic strings:

@Html.DropDownListFor(m => m.relationshipDropDownList, Model.GenderSelectList);

and in the ViewModel you'd build your SelectListItems

public static List<SelectListItem> GenderSelectList
{
    get
    {
        List<SelectListItem> genders = new List<SelectListItem>();

        foreach (Gender gender in Enum.GetValues(typeof(Gender)))
        {
            genders.Add(new SelectListItem { Text = gender.ToString(), Value = gender.ToString("D"), Selected = false });
        }

        return genders;
    }
}
Jani Hyytiäinen
  • 5,293
  • 36
  • 45