2009-10-02 39 views

回答

1

<%= Html.DropDownList() %>有大約8個重載,您可以使用。您需要將枚舉映射到IEnumerable<SelectListItem>以傳遞給它。事情是這樣的:

var names = Enum.GetNames(typeof(MyEnum)); 
List<SelectListItem> items = new List<SelectListItem>(); 
foreach (var s in names) 
{ 
    items.Add(new SelectListItem() { Text = s, 
            Value = s, 
            Selected = (s == "SelectedValue") }; 
} 
+2

就個人而言,如果我這樣做,我會使用LINQ,而不是創建一個列表,然後填充它。將一件事變成一系列別的東西正是LINQ擅長的。 var items = Enum.GetNames(typeof(MyEnum))。Select(n => new SelectListItem(){Text = n,Value = n,Selected =(n ==「SelectedValue」)}); – 2009-10-02 22:20:12

2

從MVC的Contrib的FluentHtml庫已經內置了對從枚舉產生選擇框的支持。

<%= this.Select("example") 
     .Options<System.IO.FileOptions>() 
     .Selected(System.IO.FileOptions.Asynchronous) %> 

此輸出:

<select id="example" name="example"> 
    <option value="0">None</option> 
    <option value="16384">Encrypted</option> 
    <option value="67108864">DeleteOnClose</option> 
    <option value="134217728">SequentialScan</option> 
    <option value="268435456">RandomAccess</option> 
    <option selected="selected" value="1073741824">Asynchronous</option> 
    <option value="-2147483648">WriteThrough</option> 
</select>