Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a dropdownlist from an enum in ASP.NET MVC? [duplicate]

I'm trying to use the Html.DropDownList extension method but can't figure out how to use it with an enumeration.

My classes :

namespace Support_A_Tree.Models
{
    public enum Countries
    {
        Belgium,
        Netherlands,
        France,
        United_Kingdom,
        Other
    }


    [MetadataType(typeof(SupporterMetaData))]
    public partial class Person
    {
        public string Name { get; set; }
        public Countries Country { get; set; }

        public List<SelectListItem> allCountries()
        {
            List<SelectListItem> choices = new List<SelectListItem>();
            foreach (String c in Enum.GetValues(typeof(Countries)))
            {
                choices.Add(new SelectListItem() { Text = c , Value = bool.TrueString });
            }
            return choices;
        }


    }

    public class SupporterMetaData
    {
        public string Name { get; set; }

        [Required]
        public Countries Country { get; set; }
    }
}

In my VIEW I tried to get all countries, but it seems like i'm doing it wrong.

@using (Html.BeginForm())
{
    <div>
        <p style = "color: red;">@ViewBag.Message</p>
    </div>

    <div>
        <h2> You want to ... </h2>
        <p>Plant trees</p>
        @Html.CheckBoxSimple("support", new { @value = "Plant trees" })

        <p>Support us financial</p>
        @Html.CheckBoxSimple("support", new { @value = "Support financial" })
    </div>

    <input type="submit" value="Continue ">
}
like image 438
Awa Avatar asked Apr 27 '16 18:04

Awa


1 Answers

In your view you can use SelectExtensions.EnumDropDownListFor:

E.g:

@Html.EnumDropDownListFor(model => model.Countries)

given that the @model of the view has a property named Countries that is an enum type.

If you want to show a default text in the drop down (like: "Select country"). Take a look at the following question and answer.

Html.EnumDropdownListFor: Showing a default text

like image 111
Nkosi Avatar answered Oct 10 '22 17:10

Nkosi