Ich habe eine Enum
genannt CityType
Bind Enum mit Drop-Down-und legen ausgewählten Wert auf get Aktion in MVC C#
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 beim .cshtml
@Html.DropDownList("HomeCity",null,new { @style = "width:155px;", @class = "form-control" })
EnumHelper GetDescription-Klasse Beschreibung von Enum erhalten
Also, was ist dein Problem? Und Ihre'Enum' sollte nicht den Wert 'Select = 0' enthalten. Sie erstellen die Option 'null' mit einer Überladung von 'DropDownList()', die eine 'labelOption' akzeptiert. Und um dies richtig zu machen, beziehen Sie sich auf die Antworten [hier] (http://stackoverflow.com/questions/388483/how-do-you-create-a-dropdownlist-from-an-enum-in-asp-net-mvc) –
Related: https://stackoverflow.com/questions/17280906/binding-an-enum-to-a-dropdownlist-in-mvc-4/17281798 – Graham