fill ComboBox with enum c # in MVC

0

I am using MVC with C #, I have a problem as I can fill a ComboBox with @ Html.DropDownList () using an enumeration from my controller, knowing that in my ComboBox it should be placed as value (number in the enumeration) and the text (name of the country in the list)

            <div class="text-left col-md-6">
                <label class="col-sm-12 control-label" for="email-03" style="font-weight: normal;padding-left: 0px;">País</label>

                <div class="text-left col-md-4" style="padding-left: 0px;">
                    @Html.DropDownList("DDLPais", ViewBag.Pais as SelectList, new { @class = "form-control col-md-12" })

                </div>
                <br />
            </div>

in the controller

public enum Pais
{
    Mexico = 1,
    EU = 2,
    Inglaterra = 3
}

List<Pais> lstStatus = Enum.GetValues(typeof(Pais)).ToList();

ViewBag.Pais = lstStatus;
    
asked by Ivxn 15.06.2018 в 00:37
source

1 answer

0

To generate a dropdownlist from an enum, you will need to assign the properties of the element.

var lstStatus = Enum.GetValues(typeof(Pais)).Cast<Pais>().ToList().Select(x => new DropDownList
    {
        Text = x.GetDescription(),
        Value = x.GetHashCode()
    })
    ViewBag.Pais = lstStatus;

You need to add the description to your enum.

public enum Pais
{
    [DescriptionAttribute("Mexico ")]
    Mexico = 1,
    [DescriptionAttribute("EU ")]
    EU = 2,
    [DescriptionAttribute("Inglaterra ")]
    Inglaterra = 3
}
    
answered by 15.06.2018 / 01:26
source