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!

0

4 Answers 4

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)
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.