2011-11-22 105 views
2

我是ASP.NET MVC 3新手。我試圖在下拉列表中顯示一些選項。這些選項將模仿enum中的值。枚舉具有以下三個值:ASP.NET MVC 3 - 枚舉值Html.DropDownList

public enum Gender 
{ 
    Male = 0, 
    Female = 1, 
    NotSpecified=-1 
} 

我想生成以下HTML

<select> 
    <option value="0">Male</option> 
    <option value="1">Female</option> 
    <option value="2">Not Specified</option> 
</select> 

我試圖用剃刀要做到這一點,但我有點失落。目前我有:

@Html.DropDownList("relationshipDropDownList", WHAT GOES HERE?) 

請注意,我無法編輯枚舉。感謝您的幫助!

回答

1

這樣的事情...

//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) 
0

有一個答案對同一問題here

接受的答案有一個擴展方法來枚舉轉換成一個選擇列表的,它可以像使用此

在控制器

ViewBag.Relationships = Gender.ToSelectList(); 

在部分

@Html.DropDownList("relationshipDropDownList", ViewBag.Relationships) 
0
@Html.DropDownList("relationshipDropDownList", Model.GenderSelectList); 

不過,我寧願用DropDownListFor避免使用魔法字符串:

@Html.DropDownListFor(m => m.relationshipDropDownList, Model.GenderSelectList); 

,並在ViewModel你建立你的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; 
    } 
} 
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 = "" })