Binden Enum mit dropdown Menü und setzen Sie selected Wert auf action im MVC C#

Ich habe eine Enum genannt CityType

public enum CityType
    {
        [Description("Select City")]
        Select = 0,

        [Description("A")]
        NewDelhi = 1,

        [Description("B")]
        Mumbai = 2,

        [Description("C")]
        Bangalore = 3,

        [Description("D")]
        Buxar = 4,

        [Description("E")]
        Jabalpur = 5
    }

Generieren Liste von Enum

IList<SelectListItem> list = Enum.GetValues(typeof(CityType)).Cast<CityType>().Select(x =>    new SelectListItem(){ 
    Text = EnumHelper.GetDescription(x), 
    Value = ((int)x).ToString()
}).ToList(); 

int city=0; 
if (userModel.HomeCity != null) city= (int)userModel.HomeCity;
ViewData["HomeCity"] = new SelectList(list, "Value", "Text", city);

Binden .cshtml

@Html.DropDownList("HomeCity",null,new { @style = "width:155px;", @class = "form-control" })

EnumHelper GetDescription Klasse, um eine Beschreibung des Enum -

Also, was ist dein problem? Und Ihre enum sollte nicht enthalten die Select = 0 Wert. Sie erstellen die null option mit einer überlast von DropDownList() akzeptiert eine labelOption. Und um dies zu tun korrekt, beziehen sich die Antworten here
Verwandte: stackoverflow.com/questions/17280906/...

InformationsquelleAutor Satish Singh | 2013-08-22

Schreibe einen Kommentar