Phone Developer
Phone Developer

Reputation: 1461

ASP.NET MVC 3 - Html.DropDownList for Enumerated values

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!

Upvotes: 2

Views: 8931

Answers (4)

Thulasiram
Thulasiram

Reputation: 8552

    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 = "" })

Upvotes: 0

Jani Hyyti&#228;inen
Jani Hyyti&#228;inen

Reputation: 5407

@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;
    }
}

Upvotes: 0

Dallas
Dallas

Reputation: 2227

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)

Upvotes: 0

dotjoe
dotjoe

Reputation: 26940

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)

Upvotes: 1

Related Questions